美文网首页
Unity--Xml序列化和反序列化(排行榜实例)

Unity--Xml序列化和反序列化(排行榜实例)

作者: ZZ曾帅 | 来源:发表于2017-11-07 19:03 被阅读0次
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using System.Xml;
    using System.Linq;
    using System.Xml.Linq;
    using System.IO;
    using System.Xml.Serialization;
    
    public class XmlRecord : MonoBehaviour {
    
        [System.Serializable]   //让类变成在编辑器中可见
        
        public class MyScore:System.IComparable{    //继承IComparable接口可以变成可比较的类
            public int CompareTo(object obj)    //实现接口的方法
            {
                MyScore my = (MyScore)obj;
                if(this.Score < my.Score){
                    return -1;
                }else{
                    return 1;
                }
            }
            public string Name;
            public int Score;
            public MyScore(string n,int s){     //构造器
                Name = n;
                Score = s;
            }
            public MyScore(){
                
            }
        }
        public List<MyScore> myScore = new List<MyScore>();         //储存分数和姓名的链表
        private bool isChangeList = false;      //判断链表是否变化
        public void AddMyScore(string n,int s){         //往链表中添加数据
            MyScore my = new MyScore(n,s);
            if(myScore.Count < 10){         //排行榜只取前十位,所以在前十个加的时候一定可以直接加进去
                myScore.Add(my);
                isChangeList = true;
            }else{
                if(myScore[9].Score < my.Score){        //否则要和第十个比较大小,如果比第十个大,则替换他
                    isChangeList = true;
                    myScore[9] = my;
                }
            }
            myScore.Sort();         //排序
    
            myScore.Reverse();      //反转
        }
        void OnApplicationQuit(){       //当游戏退出的时候
            print("Quit");
            if(isChangeList){
                System.Type type = typeof(List<MyScore>);       //先获取要序列化的类型
                XmlSerializer xs = new XmlSerializer(type);     //list与序列化绑定
                FileStream fs = null;       //建立空的文件流
                try         //捕获异常
                {
                    fs = new FileStream(Application.persistentDataPath + "/Score.xml", FileMode.Create);        //新建一个xml文件,如果存在就覆盖,不存在就创建
                }
                catch (System.Exception e)
                {
                    Debug.LogError(e);
                }
                finally
                {
                    StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);      //使得xml字符编码为UTF8
                    xs.Serialize(sw, myScore);      //进行序列化
                    sw.Close();         //使用完关闭
                    fs.Close();
                }
            }
            
        }
        // Use this for initialization
        void Start () {
            Init();
        }
        void Init(){
            Debug.Log(Application.persistentDataPath);      //安卓路径,关键点
    
            System.Type type = typeof(List<MyScore>);
            XmlSerializer xs = new XmlSerializer(type);
    
            if (File.Exists(Application.persistentDataPath + "/score.xml"))
            {
                print("存在文件");
                FileStream fs = null;
                try
                {
                    fs = new FileStream(Application.persistentDataPath + "/Score.xml", FileMode.Open);      //打开文件获取文件流
                }
                catch (System.Exception e)
                {
                    Debug.LogError(e.Message);
                }
                finally
                {
                    myScore = (List<MyScore>)xs.Deserialize(fs);        //进行反序列化
                    fs.Close();
                }
    
            }
            else
            {
                print("不存在文件");
    
                myScore.Add(new MyScore("未命名", 0));
                myScore.Add(new MyScore("未命名1", 1));
                myScore.Add(new MyScore("未命名2", 2));
                myScore.Add(new MyScore("未命名3", 3));
                FileStream fs = null;
                try
                {
                    fs = new FileStream(Application.persistentDataPath + "/Score.xml", FileMode.Create);
                }
                catch (System.Exception e)
                {
                    Debug.LogError(e);
                }
                finally
                {
                    StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
                    xs.Serialize(sw, myScore);
                    sw.Close();
                    fs.Close();
                }
    
            }
        }
        // Update is called once per frame
        void Update () {
            if(Input.GetMouseButtonDown(0)){
                string name = (char)Random.Range(48,97) + "";
                int score = Random.Range(0,100);
                AddMyScore(name,score);
                print("玩家 "+name+" 获得了 "+score);
            }
            if(Application.platform == RuntimePlatform.Android && (Input.GetKeyDown(KeyCode.Escape))){      //安卓的退出键
                Application.Quit();
            }
            if (Application.platform == RuntimePlatform.Android && (Input.GetKeyDown(KeyCode.Home)))        //安卓的Home键
            {
                Application.Quit();
            }
        }
    }
    
    

    相关文章

      网友评论

          本文标题:Unity--Xml序列化和反序列化(排行榜实例)

          本文链接:https://www.haomeiwen.com/subject/zqzjmxtx.html