在Unity和C#中使用JSON加载精灵

时间:2018-02-25 11:06:04

标签: c# json unity3d

我在文本中使用了JSON并且它工作正常但是当我向它添加Sprite时没有加载sprite / image它会给出一个null语句。这是我的每个脚本的代码。 CLICK HERE TO SEE THE PROBLEM

首先是我的JSON脚本

{
  "Vehicles": [
    {
      "Make": "Toyota",
      "Model": "Camry",
      "Wheels": 4,
      "CarImage": "Assets/Resources/Sprites/Slide1.png"
    },
    {
      "Make": "Yamaha",
      "Model": "Di ko balo",
      "Wheels": 2,
      "CarImage": "Assets/Resources/Sprites/Slide1.png"
    },
    {
      "Make": "Ford",
      "Model": "Ranger",
      "Wheels": 4,
      "CarImage": "Assets/Resources/Sprites/Slide1.png"
    }
  ]
}

其次是在Game Object中显示的可序列化公共类

public string Make;
public string Model;
public int Wheels;
public Sprite CarImage;

第三是创建一个对象列表

public List<Vehicles> Vehicles = new List<Vehicles>();

最后将在游戏对象

中插入的脚本
void Start () {
    TextAsset asset = Resources.Load("Vehicles") as TextAsset;

    if (asset != null) {
        VehicleList = JsonUtility.FromJson<VehiclesLists>(asset.text);
        foreach (Vehicles vehicle in VehicleList.Vehicles)
        {
            print(vehicle.Make);
            print(vehicle.Model);
            print(vehicle.Wheels);
            print(vehicle.CarImage);
        }

    } else
    {
        print("Asset is null");
    }
}

我只需要在调试中显示精灵感谢

1 个答案:

答案 0 :(得分:0)

试试这个

 string json = "{\n  \"Vehicles\": [\n    {\n      \"Make\": \"Toyota\",\n      \"Model\": \"Camry\",\n      \"Wheels\": 4,\n      \"CarImage\": \"Assets/Resources/Sprites/Slide1.png\"\n    },\n    {\n      \"Make\": \"Yamaha\",\n      \"Model\": \"Di ko balo\",\n      \"Wheels\": 2,\n      \"CarImage\": \"Assets/Resources/Sprites/Slide1.png\"\n    },\n    {\n      \"Make\": \"Ford\",\n      \"Model\": \"Ranger\",\n      \"Wheels\": 4,\n      \"CarImage\": \"Assets/Resources/Sprites/Slide1.png\"\n    }\n  ]\n}";



          VehicleList = JsonUtility.FromJson<VehiclesLists>(json);

            foreach (var vehicle in VehicleList.Vehicles)
            {
                vehicle.CarImageSprite = Resources.Load(vehicle.CarImageStr, typeof(Sprite)) as Sprite;
                print(vehicle.CarImageStr);
            }


    public class Vehicle
    {
        public string Make { get; set; }
        public string Model { get; set; }
        public int Wheels { get; set; }
        public string CarImageStr { get; set; }
        public Sprite CarImageSprite { get; set; }
    }

    public class RootObject
    {
        public List<Vehicle> Vehicles { get; set; }
    }