unity 通过JsonUtility本地保存json数据是保存数据为空

    //保存json文件路径
    string JsonPath()
    {
        return Application.streamingAssetsPath + "/GameData.json";
    }
//游戏信息
[Serializable]
public class GameData
{
    private int  bool IsAgainGame = false;// 是否再来一次游戏
    private  bool isFirstGame;//是否是第一次游戏
    private  bool isMusicOn;//是否打开音效
    private  int gameMaxScore;// 游戏最高成绩
    private int[] bestScoreArr;//分数排名
    private int selectSkin;//选择皮肤
    private bool[] skinUnlocked;//皮肤是否解锁
    private int diamondCount;

}
 /// <summary>
    /// 保存json数据到本地
    /// </summary>
    void SaveJson()
    {
        //如果本地没有对应的json 文件,重新创建
        if (!File.Exists(JsonPath()))
        {
            File.Create(JsonPath()).Dispose();
        }
        data.SetIsFirstGame(isFirstGame);
        data.SetIsMusicOn(isMusicOn);
        data.SetGameMaxScore(gameMaxScore);
        data.SetBestScoreArr(bestScoreArr);
        data.SetSelectSkin(selectSkin);
        data.SetSkinUnlocked(skinUnlocked);
        data.SetDiamondCount(diamondCount);
      
        string json = JsonUtility.ToJson(data, true);
        File.WriteAllText(JsonPath(), json);
        Debug.Log(data.GetDiamondCount());
        Debug.Log("保存成功");
    }

问题:通过上述方法把数据保存到本地时,生成了json文件,但是json文件里边没有数据。

原因:把游戏信息里边的参数设置成了私有模式(private)

代码修改如下:

    public  bool IsAgainGame = false;
    public bool isFirstGame;//是否是第一次游戏
    public bool isMusicOn;//是否打开音效
    public int gameMaxScore;// 游戏最高成绩
    public int[] bestScoreArr;//分数排名
    public int selectSkin;//选择皮肤
    public bool[] skinUnlocked;//皮肤是否解锁
    public int diamondCount;//金币数量

之后成功生成json文件

猜你喜欢

转载自blog.csdn.net/qq_41263535/article/details/122195952
今日推荐