JsonUtility.FromJson 不能设置{ get; set; }

本文介绍如何在Unity中使用JsonUtility解析从API获取的JSON数据,并通过具体代码示例展示了如何将JSON数据映射到C#类中,解决在设置属性时遇到的问题。

  http://json2csharp.chahuo.com/ 根据json数据生成的类,如下;

/*
     *其JsonUtility.FromJson 不能设置{ get; set; },一直报空引用,需要设置实例对象异常,最后我把{ get; set; }删了就可以存进来了,我真的想······
     *public class Data {
        public string A  { get; set; }
        public string B  { get; set; }
        public string C  { get; set; }
        public string D  { get; set; }
    }

    public class RootObject {
        public List<Data> data { get; set; }
        public string total  { get; set; }
    }
     *
     */

[System.Serializable]
    public class Item
    {

        public string A;
        public string B;
        public string C;
        public string D;

    }

    // 接受 api 返回的 json 数据
    [System.Serializable]
    public class ItemData
    {

        public List<Item> data;
        public int total;

    }

    void Start()
    {
        if (!File.Exists(JsonPath()))
            {
                Debug.LogError("读取的文件不存在!");
                return;
            }
//            string jsonString = File.ReadAllText(Application.dataPath + "/Data/ItemJsonFromApi.json");
            string json = File.ReadAllText(JsonPath());
        ItemData itemDate = JsonUtility.FromJson<ItemData>(json);
        Debug.Log(itemDate.total);
        foreach (var item in itemDate.data)
        {
            Debug.Log(item.A);
        }
    }
    //保存json文件路径
    string JsonPath()
        {
            return Application.streamingAssetsPath + "/trouble.json";
        }

 

///////////json 数据

{
    "data": [
        {
            "A": "zhanXXXXXXXXXXXg",
            "B": "00000000zhangXXXXXXXX",
            "C": "gun1.png",
            "D":"DDDD"
        },
        {
            "A": 2,
            "B": "gun2",
            "C": "gun2.png",
            "D":"DDDD"
        },
        {
            "A": 3,
            "B": "gun3",
            "C": "gun1.png",
            "D":"DDDD"
        },
        {
            "A": 4,
            "B": "gun4",
            "C": "gun2.png",
            "D":"DDDD"
        }
    ],
    "total": 333
}

using UnityEngine; [System.Serializable] public class GameData { // 玩家位置数据 public Vector3 playerPosition; // 场景名称 public string currentScene; // 存档时间戳 public string saveTime; // 构造函数 public GameData() { playerPosition = Vector3.zero; currentScene = "MainMenu"; saveTime = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm"); } } using System.IO; using UnityEngine; public class SaveSystem : MonoBehaviour { public static SaveSystem Instance { get; private set; } public GameData currentData { get; private set; } private string savePath; private void Awake() { if (Instance == null) { Instance = this; DontDestroyOnLoad(gameObject); Initialize(); } else { Destroy(gameObject); } } private void Initialize() { savePath = Path.Combine(Application.persistentDataPath, "savedata.json"); LoadGame(); } // 保存游戏 public void SaveGame(Vector3 playerPosition) { currentData.playerPosition = playerPosition; currentData.currentScene = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name; currentData.saveTime = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm"); string jsonData = JsonUtility.ToJson(currentData); File.WriteAllText(savePath, jsonData); Debug.Log($"游戏已保存: {savePath}"); } // 加载游戏 public void LoadGame() { if (File.Exists(savePath)) { string jsonData = File.ReadAllText(savePath); currentData = JsonUtility.FromJson<GameData>(jsonData); } else { currentData = new GameData(); } } // 删除存档 public void DeleteSave() { if (File.Exists(savePath)) { File.Delete(savePath); currentData = new GameData(); } } // 检查存档是否存在 public bool SaveExists() { return File.Exists(savePath); } } 我现在需要增加储存当前的state有三个分别为before,win,lose
08-08
我看不太懂,这是几个相关代码,你帮我排除一下,是不是有和地块生成系统有出入的地方:using System; using System.Collections.Generic; using UnityEngine; // ScriptableObject 类,用于在 Unity 编辑器中创建 .asset 文件 [CreateAssetMenu(fileName = "新地块数据库", menuName = "地图/地块数据库", order = 1)] [Serializable] public class 地块数据库 : ScriptableObject { // 存储所有地块数据的列表 public List<地块Data> 地块列表 = new List<地块Data>(); // 添加一个地块数据 public void 添加地块(地块Data 地块) { 地块列表.Add(地块); Debug.Log($"✅ 添加地块 ({地块.X}, {地块.Y}) - {地块.生态类型}"); } // 查找指定坐标的地块 public 地块Data 查找地块(int x, int y) { return 地块列表.Find(地块 => 地块.X == x && 地块.Y == y); } // 判断某个坐标是否已存在地块 public bool 是否存在(int x, int y) { return 地块列表.Exists(地块 => 地块.X == x && 地块.Y == y); } // 保存数据库为 JSON 文件到持久化路径 public void 保存为JSON(string 文件名) { string json = JsonUtility.ToJson(new 地块数据库Wrapper { 数据 = 地块列表 }, true); string path = Application.persistentDataPath + "/" + 文件名 + ".json"; System.IO.File.WriteAllText(path, json); Debug.Log("✅ 地块数据已保存到: " + path); } // 从 JSON 文件加载数据到数据库 public void 从JSON加载(string 文件名) { string path = Application.persistentDataPath + "/" + 文件名 + ".json"; if (System.IO.File.Exists(path)) { string json = System.IO.File.ReadAllText(path); var wrapper = JsonUtility.FromJson<地块数据库Wrapper>(json); 地块列表 = wrapper.数据; Debug.Log("✅ 地块数据已从文件加载: " + path); } else { Debug.LogWarning("⚠️ 文件不存在: " + path); } } } // 包装类,用于支持 List 的 JSON 序列化 [Serializable] public class 地块数据库Wrapper { public List<地块Data> 数据; } using System; using UnityEngine; using System.Collections.Generic; [Serializable] public class 地块Data { public int X; public int Y; public string 生态类型; public List<string> 生物列表 = new List<string>(); public string 描述; public int 序号; public override string ToString() { return $"({X}, {Y}) - {生态类型}\n生物: {string.Join(", ", 生物列表)}\n描述: {描述}\n序号: {序号}"; } } using UnityEngine; using System.Collections; public class 聊天邀请管理器 : MonoBehaviour { // 单例模式 public static 聊天邀请管理器 Instance { get; private set; } [Header("引用")] public 聊天邀请弹窗 邀请弹窗; public 聊天系统 聊天系统; public bool 初始处于外出模式 = false; // 默认不进入外出模式 [Header("邀请设置")] public float 最小邀请间隔 = 10000f; public float 最大邀请间隔 = 30000f; public bool 调试模式 = true; private bool 处于外出模式 = false; private bool 正在聊天 = false; private Coroutine 邀请协程; private void Awake() { // 单例初始化 if (Instance == null) { Instance = this; DontDestroyOnLoad(gameObject); // 可选:跨场景保持 } else { Destroy(gameObject); return; } } public void 设置正在聊天(bool 聊天中) { 正在聊天 = 聊天中; if (调试模式) Debug.Log($"聊天状态变更为: {聊天中}"); if (聊天中) { if (邀请协程 != null) { StopCoroutine(邀请协程); 邀请协程 = null; } } else if (处于外出模式 && 邀请协程 == null) { 邀请协程 = StartCoroutine(等待并邀请()); } } void Start() { // 验证引用 if (邀请弹窗 == null) Debug.LogError("聊天邀请管理器:请赋值邀请弹窗!"); else Debug.Log("聊天邀请管理器:已正确引用邀请弹窗"); // 自动查找聊天系统 if (聊天系统 == null) { 聊天系统 = FindObjectOfType<聊天系统>(); if (聊天系统 == null) Debug.LogError("聊天邀请管理器:未找到聊天系统组件!"); } // 初始状态设置 处于外出模式 = 初始处于外出模式; if (处于外出模式 && !正在聊天 && 邀请协程 == null) { 邀请协程 = StartCoroutine(等待并邀请()); } } // 显示邀请 public void 显示邀请(string 开场白, System.Action 接受回调) { if (邀请弹窗 == null) { Debug.LogError("邀请弹窗未赋值,无法显示邀请"); return; } 邀请弹窗.显示弹窗( "系统消息", // 标题 开场白, // 内容(开场白) 接受回调, // 接受回调 () => // 拒绝回调 { if (调试模式) Debug.Log("邀请被拒绝"); if (处于外出模式 && !正在聊天 && 邀请协程 == null) { 邀请协程 = StartCoroutine(等待并邀请()); } } ); } // 设置外出模式 public void 设置外出模式(bool 开启) { 处于外出模式 = 开启; if (调试模式) Debug.Log($"外出模式已{(开启 ? "开启" : "关闭")}"); if (开启 && !正在聊天 && 邀请协程 == null) { 邀请协程 = StartCoroutine(等待并邀请()); } else if (!开启 && 邀请协程 != null) { StopCoroutine(邀请协程); 邀请协程 = null; } } // 等待一段时间后显示邀请 private IEnumerator 等待并邀请() { while (true) { // 随机等待时间 float 等待时间 = Random.Range(最小邀请间隔, 最大邀请间隔); if (调试模式) Debug.Log($"将在 {等待时间:F1} 秒后显示下一次邀请"); yield return new WaitForSeconds(等待时间); // 检查是否仍需要显示邀请 if (处于外出模式 && !正在聊天) { 显示邀请("默认开场白", () => { if (聊天系统 != null) { 聊天系统.打开聊天窗口(); } }); break; // 显示后退出协程,等待聊天结束后重新开始 } else if (!处于外出模式 || 正在聊天) { break; } } 邀请协程 = null; } }
最新发布
08-31
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值