untiy初识之playerPrefs 和jsonUtility结合存储数据

playerPrefs 可以将数据存储到本地。cocos egret 都有类似的 比如egret的 localstorage

playerprefs 函数比较少,只用来做存储用

untiy初识之playerPrefs 和jsonUtility结合存储数据_第1张图片

json utility 例子

using System;

[Serializable]
public class PlayerInfo {
    public int score { get; set; }
    public int highScore { get; set; }

    public int nimamapi ;
    public string[] nihao = new string[3];
    public List test1 = new List();

    public PlayerInfo() {
        score = 1 ;
        highScore = 10 ;

        nimamapi = 100;
        nihao[0] = "nihao1";
        nihao[1] = "nihao2";
        nihao[2] = "nihao3";

        test1.Add(new Vector2(0,0));
        test1.Add(new Vector2(1,1));
        test1.Add(new Vector2(3,4));
    }

    public PlayerInfo PaseJson(string jsonString) {
        return JsonUtility.FromJson(jsonString);
    }

    public string ToJson() {
        return JsonUtility.ToJson(this);
    }

    public void saveToLocal() {
        PlayerPrefs.SetString("PlayerInfo", ToJson());

        Debug.Log("~~~~~~~~~~ saveToLocal " + ToJson());
    }

    public string GetJsonStringFromLocal() {
        if (!PlayerPrefs.HasKey("PlayerInfo")) {
            PlayerPrefs.SetString("PlayerInfo", ToJson());

            string js = ToJson();
            Debug.Log("~~~~~~~~~~ GetJsonStringFromLocal " + ToJson());
        }
        return PlayerPrefs.GetString("PlayerInfo");
    }
}
        m_playerInfo = new PlayerInfo();
        string jsonData = m_playerInfo.GetJsonStringFromLocal();
        Debug.Log("~~~~~~~~~~ jsonData " + jsonData);
        m_playerInfo = m_playerInfo.PaseJson(jsonData);

        Debug.Log("~~~~~~~~~~ " + m_playerInfo);

这里打印出来的存储的json 字符串为
~~~~~~ jsonData {“nimamapi”:100,”nihao”:[“nihao1”,”nihao2”,”nihao3”],”test1”:[{“x”:0.0,”y”:0.0},{“x”:1.0,”y”:1.0},{“x”:3.0,”y”:4.0}]}

注意,这里给jsonUnitlity使用的必须是class , struct 或者monoBehavier 可序列化的类
并且 get set 的成员变量是不支持的, 必须是public 的成员变量

untiy初识之playerPrefs 和jsonUtility结合存储数据_第2张图片

你可能感兴趣的:(unity初识,Unity初识)