unity中实现json序列化

1,当涉及到游戏保存的时候,这个时候我们需要对当前游戏的物体进行保存,主要包括位置,血量等其他属性的保存,

但是unity暂时未提供这个功能,这个时候我们需要用到json,利用json序列化,将物体的信息存储为json字符串,然后通过

PlayerPrefs存到手机的存储中,下次就可以直接读取playerprefs恢复之前的游戏状态

相关操作如下:

using Newtonsoft.Json;
public static string geneateJsonStringFromCluster(GameObject targetcluster)
    {
        JsonCluster jcstr = new JsonCluster();
        Clustercontroller cc = targetcluster.GetComponent<Clustercontroller>();
        jcstr.price = cc.getAllThePrice();
        foreach (var item in cc.clusterdic)
        {
            Baseattribute bat = item.Value.GetComponent<Baseattribute>();
            string nodetype = bat.getNodeType();
            if (nodetype == "incubator")
            {
                IncubatorJson icbt = new IncubatorJson();
                bat.toBaseJson<IncubatorJson>(icbt);
                jcstr.optionNodeList(icbt);


            }
            if (nodetype == "generator")
            {
                GeneratorJson icbt = new GeneratorJson();
                bat.toBaseJson<GeneratorJson>(icbt);
                jcstr.optionNodeList(icbt);
            }
            if (nodetype == "defender")
            {
                DefenderJson icbt = new DefenderJson();
                bat.toBaseJson<DefenderJson>(icbt);
                jcstr.optionNodeList(icbt);
            }
            if (nodetype == "engine")
            {
                EngineJson icbt = new EngineJson();
                bat.toBaseJson<EngineJson>(icbt);
                jcstr.optionNodeList(icbt);
            }
            if (nodetype == "pulser")
            {
                PulserJson icbt = new PulserJson();
                bat.toBaseJson<PulserJson>(icbt);
                jcstr.optionNodeList(icbt);
            }
            if (nodetype == "cloner")
            {
                ClonerJson icbt = new ClonerJson();
                bat.toBaseJson<ClonerJson>(icbt);
                jcstr.optionNodeList(icbt);
            }
            if (nodetype == "attacker")
            {
                AttackerJson icbt = new AttackerJson();
                bat.toBaseJson<AttackerJson>(icbt);
                jcstr.optionNodeList(icbt);
            }

        }

        return JsonConvert.SerializeObject(jcstr);
}

  然后我们读取的时候 只需要就好了

JsonConvert.DeserializeObject<JsonCluster>(tempjsoncode);

  

 

posted @ 2023-09-25 18:26  wangnima666  阅读(50)  评论(0编辑  收藏  举报