游戏存档实例

1.创建Sava类

[System.Serializable]
public class Save
{
    public List<int> livingMonsterPostions=new List<int>();
    public List<int> livingMonsterTypr = new List<int>();
    public int score=0;
    public int shoot=0;

}

2.创建Sava对象

 /// <summary>
    /// 创建Sava对象并存储当前游戏状态信息
    /// </summary>
    /// <returns></returns>
    public Save CreatSaveObject()
    {
        //创建Sava对象
        Save save = new Save();
        //遍历所有的target
        //如果有激活的怪物,就把该target的位置信息和激活状态怪物的类型保存到Sava类中的list集合中
        foreach (GameObject targetGo in targets)
        {
            TargetGamagaer targetGamagaer = targetGo.GetComponent<TargetGamagaer>();
            if (targetGamagaer.nowMonsters!=null)
            {
                save.livingMonsterPostions.Add(targetGamagaer.targetPostions);
                int type = targetGamagaer.nowMonsters.GetComponent<MonstersManagaer>().monsterType;
                save.livingMonsterTypr.Add(type);
            }
        }
        //把score和shootnum保存在sava对象里
        save.score = UIManagaer._instance.score;
        save.shoot = UIManagaer._instance.shootNum;
        //返回sava对象
        return save;
    }

3.二进制的存档

//二进制存档
    public void SavaByBin()
    {
        //序列化过程(将对象转化为字节流)

        Save save = CreatSaveObject();//创建Sava对象
        //创建一个二进制格式化程序
        BinaryFormatter bf = new BinaryFormatter();
        //创建一个流文件
        FileStream fileStream = File.Create(Application.dataPath+ "/StreamingFile"+"/ByBin.txt");
        //用二进制格式化程序的序列方法来序列化Sava对象,参数为创建的流文件和需要的序列化的对象
        bf.Serialize(fileStream,save);
        //关闭流
        fileStream.Close();
    }

4.二进制读档

  //二进制读档
    public void LoadByBin()
    {
        //反序列化过程(二进制文件到对象)

        //创建一个二进制格式化的程序
        BinaryFormatter bf = new BinaryFormatter();
        //打开文件流
        FileStream fileStream = File.Open(Application.dataPath+ "/StreamingFile"+ "/ByBin.txt",FileMode.Open);
        //调用反序列化的方法,将文件流转换为一个Sava对象
      Save save=(Save) bf.Deserialize(fileStream);
        //关闭文件流
        fileStream.Close();
        SetGame(save);
    }

5.Json存档

 //Json存档
    public void SavaByJson()
    {
        //创建Sava对象
        Save save = CreatSaveObject();

        //保存地址
        string filePath = Application.dataPath + "/StreamingFile" + "/ByJson.json";
        //利用JsonMapper方法将sava对象转化为Json格式的字符串
        string savaJsonStr = JsonMapper.ToJson(save);
        //将字符串写入到文件中
        //创建一个StreamWrite并把字符串写入到文件中
        StreamWriter sw = new StreamWriter(filePath);
        sw.Write(savaJsonStr);
        //关闭StreamWrite
        sw.Close();

        UIManagaer._instance.ShowMassage("保存成功");
    }

6.Json读档

 //Json读档
    public void LoadByJson()
    {
        string filePath = Application.dataPath + "/StreamingFile" + "/ByJson.json";
        if (File.Exists(filePath))
        {
            //创建一个StreamReader,用来读取流
            StreamReader sr = new StreamReader(filePath);
            //将读取到的流赋值给Jsonstr
            string jsonStr = sr.ReadToEnd();
            //关闭
            sr.Close();

            //将字符串jsonStr转换为sava对象
            Save save = JsonMapper.ToObject<Save>(jsonStr);
            SetGame(save);
            UIManagaer._instance.ShowMassage("");
        }
        else
        {
            UIManagaer._instance.ShowMassage("未找到保存文件");

        }
    }

7.XML存档

 //XML存档
    public void SavaByXML()
    {
        Save save = CreatSaveObject();
        //创建XML的存储路径
        string filePath = Application.dataPath + "/StreamingFile" + "/ByXML.txt";

        //创建XML文档
        XmlDocument xmlDoc = new XmlDocument();
        //创建根节点(最上层) 
        XmlElement root = xmlDoc.CreateElement("sava");
        //设置根节点的值
        root.SetAttribute("name","savaFile1");
        //创建其他节点
        XmlElement target;
        XmlElement targetPostion;
        XmlElement monsterType;
        //通过遍历sava中存储的数据,将数据转换成XML格式
        for (int i = 0; i < save.livingMonsterPostions.Count; i++)
        {
            target = xmlDoc.CreateElement("target");//把创建的元素转换成XML格式
         
            //设置元素的InnerText值
            targetPostion = xmlDoc.CreateElement("targetPostion");
            targetPostion.InnerText = save.livingMonsterPostions[i].ToString();
            monsterType = xmlDoc.CreateElement("monsterType");
            monsterType.InnerText = save.livingMonsterTypr[i].ToString();

            //设置节点之间的层级关系root-target--(targetPostion,targetPostion)
            target.AppendChild(targetPostion);
            target.AppendChild(monsterType);
            root.AppendChild(target);
        }
        //设置分数和设计数的层级,并赋值 root--(target--(targetPostion,targetPostion),score,shootNum)
        XmlElement shootNum = xmlDoc.CreateElement("shootNum");
        shootNum.InnerText = save.shoot.ToString();
        root.AppendChild(shootNum);

        XmlElement score = xmlDoc.CreateElement("score");
        score.InnerText = save.score.ToString();
        root.AppendChild(score);

        xmlDoc.AppendChild(root);
        xmlDoc.Save(filePath);
        if (File.Exists(Application.dataPath + "/StreamingFile" + "/ByXML.txt"))
        {
            UIManagaer._instance.ShowMassage("保存成功");
        }
    }

8.XML读档

 //XML读档
    public void LoadByXML()
    {
        string filePath = Application.dataPath + "/StreamingFile" + "/ByBin.txt";
        if (File.Exists(filePath))
        {
            Save save = new Save();

            //加载XML文档
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(filePath);
            //通过节点名称获取节点元素 结果为XMLNodeList类型
            XmlNodeList targets = xmlDoc.GetElementsByTagName("target");
            //遍历所有的target节点
            if (targets.Count!=0)
            {
                foreach (XmlNode target in targets) //遍历所有的target节点
                {
                    //获得所有子节点的值(InnerText)
                    XmlNode targetPostion = targets[0];
                    int targetPostionIndex = int.Parse (targetPostion.InnerText);
                    save.livingMonsterPostions.Add(targetPostionIndex);//把得到的值存到Save中

                    XmlNode monderType = targets[1];
                    int monderTypeIndex = int.Parse(monderType.InnerText);
                    save.livingMonsterTypr.Add(monderTypeIndex);
                }
            }
            //得到存储的设计数和分数
            XmlNodeList shootNum = xmlDoc.GetElementsByTagName("shootNum");
            int shootNumCount=int.Parse (shootNum[0].InnerText);
            save.shoot = shootNumCount;


            XmlNodeList score = xmlDoc.GetElementsByTagName("score");
            int scoreNum = int.Parse(shootNum[0].InnerText);
            save.shoot = scoreNum;
            SetGame(save);
            UIManagaer._instance.ShowMassage("");
        }
        else
        {
            UIManagaer._instance.ShowMassage("未找到保存文件");
        }
    }
上一篇:XML操作实验


下一篇:xml操作