You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中游戏状态字典的序列化保存与加载代码实现求助

Unity 游戏状态字典的序列化保存与加载实现

问题说明

你之前尝试的序列化代码存在语法错误,且未完成文件读写的完整流程,导致只能获取第一个元素。下面提供基于Newtonsoft.Json(Unity官方推荐的第三方Json库)的完整实现方案,解决字典的保存与加载问题。

前置准备

确保你的Unity项目已安装Newtonsoft.Json:通过Package Manager搜索com.unity.nuget.newtonsoft-json并安装。

完整代码修改

首先确保GameState类标记为可序列化:

[Serializable]
public class GameState
{
    public string Key;
    public string Value;
}

然后修改你的AppManager代码,添加保存、加载方法,并调整初始化逻辑:

using UnityEngine;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.IO;

public class AppManager : MonoBehaviour
{
    [SerializeField] private List<GameState> _startingGameStates = new List<GameState>();
    private Dictionary<string, string> _gameStateDictionary = new Dictionary<string, string>();
    // 保存文件路径,存在Unity持久化目录
    private string _saveFilePath;

    public delegate void OnStateChangedDelegate();
    public OnStateChangedDelegate OnStateChanged;

    void Awake()
    {
        DontDestroyOnLoad(gameObject);
        // 初始化保存路径
        _saveFilePath = Path.Combine(Application.persistentDataPath, "GameStates.json");
        // 优先加载本地保存的状态,加载失败则使用初始状态
        if (!LoadGameStates())
        {
            ResetGameStates();
        }
    }

    void ResetGameStates()
    {
        _gameStateDictionary.Clear();
        foreach (var gs in _startingGameStates)
        {
            if (gs != null && !string.IsNullOrEmpty(gs.Key))
            {
                _gameStateDictionary[gs.Key] = gs.Value;
            }
        }
        OnStateChanged?.Invoke();
    }

    public GameState GetStartingGameState(string key)
    {
        return _startingGameStates.Find(gs => gs != null && gs.Key.Equals(key));
    }

    public bool SetGameState(string key, string value)
    {
        if (string.IsNullOrEmpty(key) || value == null) return false;

        _gameStateDictionary[key] = value;
        OnStateChanged?.Invoke();
        // 修改状态后自动保存
        SaveGameStates();
        return true;
    }

    // 保存游戏状态到本地文件
    private bool SaveGameStates()
    {
        try
        {
            string json = JsonConvert.SerializeObject(_gameStateDictionary, Formatting.Indented);
            File.WriteAllText(_saveFilePath, json);
            Debug.Log($"游戏状态已保存到:{_saveFilePath}");
            return true;
        }
        catch (System.Exception e)
        {
            Debug.LogError($"保存失败:{e.Message}");
            return false;
        }
    }

    // 从本地文件加载游戏状态
    private bool LoadGameStates()
    {
        if (!File.Exists(_saveFilePath))
        {
            Debug.Log("未找到保存文件,使用初始状态");
            return false;
        }

        try
        {
            string json = File.ReadAllText(_saveFilePath);
            var loadedDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
            if (loadedDict != null)
            {
                _gameStateDictionary = loadedDict;
                OnStateChanged?.Invoke();
                Debug.Log("游戏状态加载成功");
                return true;
            }
            return false;
        }
        catch (System.Exception e)
        {
            Debug.LogError($"加载失败:{e.Message}");
            return false;
        }
    }

    // 可选:提供外部调用的保存方法
    public void ForceSave()
    {
        SaveGameStates();
    }
}

关键说明

  • 持久化路径:使用Application.persistentDataPath确保文件能跨平台正确存储(Windows、Mac、移动端均适用)
  • 自动保存:在SetGameState方法末尾自动调用保存,确保状态修改后立即持久化
  • 异常处理:添加了try-catch捕获读写异常,避免程序崩溃
  • 加载优先级:启动时优先加载本地保存的状态,没有保存文件才使用初始列表初始化

内容的提问来源于stack exchange,提问作者Christopher Meyer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 03:05:40