Unity JsonUtility使用

2022-06-22  本文已影响0人  114105lijia

1、先建立模型

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[Serializable]
public class InfoModel
{
    public string des;
    public float position_x;
    public float position_y;
    public float position_z;
    public float speed;
    public PrefabModel android;
}

[Serializable]
public class PrefabModel
{
    public AssetBundleModel fbx;
    public AssetBundleModel video;
}

[Serializable]
public class AssetBundleModel
{
    public string url;
    public string name;
}

public class ModelItemData
{
    public List<InfoModel> data;
    public int selectIndex;
}

2、使用UnityWebRequest请求Json

public IEnumerator GetRequest(string url)
    {
        UnityWebRequest request = UnityWebRequest.Get(url);
        request.timeout = 10;

        yield return request.SendWebRequest();

        if (request.result != UnityWebRequest.Result.Success)
        {
            Debug.Log(request.error);
        }
        else
        {
            string json = request.downloadHandler.text;
            ModelItemData resultModel = JsonUtility.FromJson<ModelItemData>(json);

            InfoModel model = resultModel.data[resultModel.selectIndex];
            speed = model.speed;
        }
    }

3、本地测试json

{
  "data": [
    {
      "position_x": -615,
      "position_y": 1132,
      "position_z": -1615,
      "des": "科",
      "speed": "100",
      "android": {
        "fbx": {
          "url": "http://10.119.90.62:8080/assetbundles/android/kesheng_android.unity3d",
          "name": "科广场"
        },
        "video": {
          "url": "http://10.119.90.62:8080/assetbundles/android/video.unity3d",
          "name": "视频"
        }
      }
    },
    {
      "position_x": 10.4,
      "position_y": 68.9,
      "position_z": -16.9,
      "des": "科盛",
      "speed": "2",
      "android": {
        "fbx": {
          "url": "http://10.119.90.62:8080/assetbundles/android/ks9.unity3d",
          "name": "Untitled 2"
        },
        "video": {
          "url": "http://10.119.90.62:8080/assetbundles/android/video.unity3d",
          "name": "视频"
        }
      }
    }
  ],
  "selectIndex": "1"
}
上一篇下一篇

猜你喜欢

热点阅读