unity 常用的數(shù)據(jù)讀取與存儲的方法(PlayerPrefs窒悔、XML、Json)解讀

PlayerPrefs

PlayerPrefs是unity中一個用于本地持久化保存與讀取的類。它以鍵值對的形式將數(shù)據(jù)保存在文件中珍策,
然后程序可以根據(jù)這個名稱取出上次保存的數(shù)值蹭劈。
PlayerPrefs類支持3中數(shù)據(jù)類型的保存和讀取,浮點(diǎn)型塔逃,整形立轧,和字符串型。
分別對應(yīng)的函數(shù)為:
SetInt();保存整型數(shù)據(jù)疆导;
GetInt();讀取整形數(shù)據(jù);
SetFloat();保存浮點(diǎn)型數(shù)據(jù)芒率;
GetFlost();讀取浮點(diǎn)型數(shù)據(jù)匪蟀;
SetString();保存字符串型數(shù)據(jù);
GetString();讀取字符串型數(shù)據(jù);

用法如下:


//PlayerPrefs 的存儲功能

  PlayerPrefs.SetInt ("yong", 110);
  
  PlayerPrefs.SetString (m_UserName, m_PassWord);
  //讀取數(shù)據(jù)功能
  
  print (PlayerPrefs.GetInt ("yong"));
  
  // 輸出為110
  
  //提供的其他方法

PlayerPrefs.DeleteKey (key) //刪除指定數(shù)據(jù)

PlayerPrefs.DeleteAll() //刪除全部鍵 

PlayerPrefs.HasKey (key)//判斷數(shù)據(jù)是否存在的方法

if (PlayerPrefs.HasKey("isShow"))
{
  //TODO
}
  

XML

1、引入命名空間


using System.Xml;

2缓升、創(chuàng)建XML文檔


// 創(chuàng)建XML文檔
  void CreatXML ()
  {
    // 創(chuàng)建一個聲明
    XmlDeclaration dec = doc.CreateXmlDeclaration ("1.0", "UTF-8", null);
    // 將聲明拼接到文檔中去
    doc.AppendChild (dec);

    //創(chuàng)建一個根元素節(jié)點(diǎn)
    XmlNode rootNode = doc.CreateNode (XmlNodeType.Element, "Transform", null);
    // 對這個根元素節(jié)點(diǎn)添加屬性
    XmlAttribute attr = doc.CreateAttribute ("name");
    attr.Value = "YourCube";   //給屬性賦值
    //將剛剛創(chuàng)建的屬性放進(jìn)根元素節(jié)點(diǎn)標(biāo)簽中去
    rootNode.Attributes.SetNamedItem (attr);

    // 拼接到xml文檔里去
    doc.AppendChild (rootNode);
    // 效果展示  <Transform name="MyCube" tag="CubeTag">

    // 創(chuàng)建一個子元素 添加到根元素節(jié)點(diǎn)中
    XmlElement pos = doc.CreateElement ("Position");

    XmlElement pos_X = doc.CreateElement ("x");
    XmlElement pos_Y = doc.CreateElement ("y");
    XmlElement pos_Z = doc.CreateElement ("z");

    pos_X.InnerText = "78";
    pos_Y.InnerText = "30";
    pos_Z.InnerText = "56";

    pos.AppendChild (pos_X);
    pos.AppendChild (pos_Y);
    pos.AppendChild (pos_Z);

    // 拼接到根節(jié)點(diǎn)中去
    rootNode.AppendChild (pos);

    // 記得保存文檔
    //Application.dataPath 路徑就是Assets文件夾
    // 記得在文件前寫/ 表示在這個文件夾下
    doc.Save (Application.dataPath + "/XML/MonoCodeXML.xml");
  } 

3膘螟、解析XML文檔


// 解析XML文檔
  void AnalyzeXML ()
  {
    // 首先拿到文檔 [用xml文檔實(shí)例去加載這個文檔]
    doc.Load (Application.dataPath + "/XML/MonoCodeXML.xml");

    //根據(jù)文檔的數(shù)據(jù)結(jié)構(gòu), 來分析如何獲取想要的數(shù)據(jù)

    // 拿到根元素節(jié)點(diǎn)
    XmlElement root = doc.DocumentElement;
    //print (root.Name);
    // root.FirstChild 就是這一層級下面的一個子元素節(jié)點(diǎn)
    XmlNode pos_X = root.FirstChild.FirstChild;

    // X子節(jié)點(diǎn)中存儲的數(shù)據(jù)內(nèi)容
    string pos_X_String = pos_X.InnerText;
    //print (pos_X_String);

    //或者通過層級路徑拿到這個節(jié)點(diǎn)的內(nèi)容
    XmlNode pos_x = root.SelectSingleNode ("/Transform/Position/x");
    print (pos_x.InnerText);
  } 

4蕴潦、完整腳本



using UnityEngine;
using System.Collections;
using System.Xml;

public class CreatXMLScript : MonoBehaviour
{

  // 創(chuàng)建一個文檔
  XmlDocument doc = new XmlDocument ();

  void Start ()
  {
    CreatXML ();
    AnalyzeXML ();
  }

  // 創(chuàng)建XML文檔
  void CreatXML ()
  {
    // 創(chuàng)建一個聲明
    XmlDeclaration dec = doc.CreateXmlDeclaration ("1.0", "UTF-8", null);
    // 將聲明拼接到文檔中去
    doc.AppendChild (dec);


    //創(chuàng)建一個根元素節(jié)點(diǎn)
    XmlNode rootNode = doc.CreateNode (XmlNodeType.Element, "Transform", null);
    // 對這個根元素節(jié)點(diǎn)添加屬性
    XmlAttribute attr = doc.CreateAttribute ("name");
    attr.Value = "YourCube";   //給屬性賦值
    //將剛剛創(chuàng)建的屬性放進(jìn)根元素節(jié)點(diǎn)標(biāo)簽中去
    rootNode.Attributes.SetNamedItem (attr);

    // 拼接到xml文檔里去
    doc.AppendChild (rootNode);
    // 效果展示  <Transform name="MyCube" tag="CubeTag">


    // 創(chuàng)建一個子元素 添加到根元素節(jié)點(diǎn)中
    XmlElement pos = doc.CreateElement ("Position");

    XmlElement pos_X = doc.CreateElement ("x");
    XmlElement pos_Y = doc.CreateElement ("y");
    XmlElement pos_Z = doc.CreateElement ("z");

    pos_X.InnerText = "78";
    pos_Y.InnerText = "30";
    pos_Z.InnerText = "56";

    pos.AppendChild (pos_X);
    pos.AppendChild (pos_Y);
    pos.AppendChild (pos_Z);

    // 拼接到根節(jié)點(diǎn)中去
    rootNode.AppendChild (pos);


    // 記得保存文檔
    //Application.dataPath 路徑就是Assets文件夾
    // 記得在文件前寫/ 表示在這個文件夾下
    doc.Save (Application.dataPath + "/XML/MonoCodeXML.xml");

  }


  // 解析XML文檔
  void AnalyzeXML ()
  {
    // 首先拿到文檔 [用xml文檔實(shí)例去加載這個文檔]
    doc.Load (Application.dataPath + "/XML/MonoCodeXML.xml");

    //根據(jù)文檔的數(shù)據(jù)結(jié)構(gòu), 來分析如何獲取想要的數(shù)據(jù)

    // 拿到根元素節(jié)點(diǎn)
    XmlElement root = doc.DocumentElement;
    //print (root.Name);
    // root.FirstChild 就是這一層級下面的一個子元素節(jié)點(diǎn)
    XmlNode pos_X = root.FirstChild.FirstChild;

    // X子節(jié)點(diǎn)中存儲的數(shù)據(jù)內(nèi)容
    string pos_X_String = pos_X.InnerText;
    //print (pos_X_String);

    //或者通過層級路徑拿到這個節(jié)點(diǎn)的內(nèi)容
    XmlNode pos_x = root.SelectSingleNode ("/Transform/Position/x");
    print (pos_x.InnerText);
  }
}
 

Json 數(shù)據(jù)解析

1蝗碎、JsonUtility untiy 自帶的解析工具 無需引用命名空間


using UnityEngine;

using System.Collections.Generic;

//此腳本使用的是System.Json 來操作JSON數(shù)據(jù)的
//將System.Json.dll 拉到unity  Plugins 文件夾下
// System.Json.dll 文件位置   unity安裝位置下
//  Editor\Data\Mono\lib\mono\unity\System.Json.dll
using System.Json;

//數(shù)據(jù)流的寫入和讀取
using System.IO;

//讓編輯器刷新資源
using UnityEditor;

using System.Text;

using System;

public class CreatJsonScript : MonoBehaviour
{
  void Start()
    {
        // 使用代碼創(chuàng)建JSON 保存數(shù)據(jù)
        //CreatJSONData ();
        // 解析JSON
        ParseJSONData();
    }

    // 創(chuàng)建json
    void CreatJSONData()
    {
        // 寫一個大括號
        JsonObject Students = new JsonObject();
       
        // Q W E R
        JsonObject message_1 = new JsonObject();
        JsonObject message_2 = new JsonObject();
        JsonObject message_3 = new JsonObject();
        JsonObject message_4 = new JsonObject();

        // 填充數(shù)據(jù)
        message_1.Add("Subject", "語文");
        message_1.Add("Stage", "一考");
        message_1.Add("Score", "93");
        message_1.Add("Ranking", "7");

        message_2.Add("Subject", "數(shù)學(xué)");
        message_2.Add("Stage", "一考");
        message_2.Add("Score", "95");
        message_2.Add("Ranking", "5");

        message_3.Add("Subject", "英語");
        message_3.Add("Stage", "一考");
        message_3.Add("Score", "96");
        message_3.Add("Ranking", "4");

        message_4.Add("Subject", "物理");
        message_4.Add("Stage", "一考");
        message_4.Add("Score", "99");
        message_4.Add("Ranking", "2");

        // 信息數(shù)組
        JsonArray MessageArr = new JsonArray();
        MessageArr.Add(message_1);
        MessageArr.Add(message_2);
        MessageArr.Add(message_3);
        MessageArr.Add(message_4);

        Students.Add("Messages", MessageArr);
        Students.Add("StudentName", "小明");
        Students.Add("StudentGrade", 6);
        Students.Add("StudentID", 258);

        print (Students.ToString ());

        // 拓展-- 數(shù)據(jù)留存檔
        // 創(chuàng)建數(shù)據(jù)流的寫入
        StreamWriter writer = new StreamWriter(Application.dataPath + "/Json/MySystemJSON.txt");
        Students.Save(writer);
        //自動裝載緩沖區(qū)
        writer.AutoFlush = true;

        writer.Close();

        //讓編輯器刷新資源
        AssetDatabase.Refresh();
    }

    void ParseJSONData()
    {
        // 本地文件的讀取
        FileInfo file = new FileInfo(Application.dataPath + "/Json/MySystemJSON.txt");
        StreamReader reader = new StreamReader(file.OpenRead(), Encoding.UTF8);
        string str = reader.ReadToEnd();

       // print (str);
        reader.Close();
        // 釋放資源
        reader.Dispose();
        // 開始解析
        StudentInfo m_StudentInfo = JsonUtility.FromJson<StudentInfo>(str);
        
        for (int i = 0; i < m_StudentInfo.Messages.Count; i++)
        {
            print(m_StudentInfo.Messages[i].Score); //93 95 96 99
        }
    }
    //創(chuàng)建數(shù)據(jù)模型 接受解析數(shù)據(jù) [因?yàn)槲覀兪敲嫦驅(qū)ο箝_發(fā)的]
    // 將我們在需要數(shù)據(jù)的地方直接使用類就可以點(diǎn)出這個模型

    //序列化  你發(fā)個qq 消息別人接收你的qq消息 不會分別將不同的數(shù)據(jù)類型發(fā)送或接收
    // 序列化后 相當(dāng)于將消息編碼加密 解密
    //[SerializeField] 修飾私有字段的 [強(qiáng)制將腳本中的私有變量在unity面板中出現(xiàn) 可以實(shí)現(xiàn)引用拖拽 但是其他腳本還是拿不到這個變量]


    //[Serializable]  修飾對象 作用 將對象序列化為二進(jìn)制數(shù)據(jù)流 byte 類型  傳輸數(shù)據(jù)或解析數(shù)據(jù)

    [Serializable]
    public class Message
    {
        public string Subject = "";
        public string Stage = "";
        public string Score = "";
        public string Ranking = "";
    }

    [Serializable]
    public class StudentInfo
    {
        public List<Message> Messages = new List<Message>();
        public string StudentName = "";
        public float StudentGrade;
        public float StudentID;
    }
}
 

system.json創(chuàng)建的json數(shù)據(jù)結(jié)構(gòu)如下:


{
    "Messages": [{
        "Subject": "語文",
        "Stage": "一考",
        "Score": "93",
        "Ranking": "7"
    }, {
        "Subject": "數(shù)學(xué)",
        "Stage": "一考",
        "Score": "95",
        "Ranking": "5"
    }, {
        "Subject": "英語",
        "Stage": "一考",
        "Score": "96",
        "Ranking": "4"
    }, {
        "Subject": "物理",
        "Stage": "一考",
        "Score": "99",
        "Ranking": "2"
    }],
    "StudentName": "小明",
    "StudentGrade": 6,
    "StudentID": 258
}

2谜叹、JsonMapper 需引用命名空間 using LitJson; //需要將LitJson加到Plugins里面

LitJson下載 https://pan.baidu.com/s/1eeJn8H8EO7wRxqcK32J-Ug


using UnityEngine;
using System.Collections;
using LitJson;
using System.IO;
using UnityEditor;
using System.Text;
using System;

public class LitJSONScript : MonoBehaviour
{
      void Start()
    {
        //使用LitJSON創(chuàng)建JSON數(shù)據(jù)
      //  CreatJSONByLit ();

        // 使用LitJSON解析數(shù)據(jù)
        ParseJSONLit();
    }

    void CreatJSONByLit()
    {
        //創(chuàng)建一個JSON結(jié)構(gòu)的實(shí)例
        JsonData Students = new JsonData();
        Students["StudentName"] = "xioaming";
        Students["StudentGrade"] =7;
        Students["StudentID"] = 122;

        Students["Messages"] = new JsonData();

        // 小技能
        JsonData message_1 = new JsonData();

        message_1["Subject"] = "Chinese";
        message_1["Stage"] = "First";
        message_1["Score"] = "115";
        message_1["Ranking"] = "6";

        JsonData message_2 = new JsonData();

        message_2["Subject"] = "Maths";
        message_2["Stage"] = "First";
        message_2["Score"] = "119";
        message_2["Ranking"] = "2";

        Students["Messages"].Add(message_1);
        Students["Messages"].Add(message_2);

        print(Students.ToJson());

        // 保存到本地 并刷新
        SaveJson(Students.ToJson());
    }

    private void SaveJson(string json)
    {
        string path = Application.dataPath + "/Json/MyLitJsonByMono.txt";
        // 文件流創(chuàng)建一個文本文件
        FileStream file = new FileStream(path, FileMode.Create);
        //得到字符串的UTF8 數(shù)據(jù)流
        byte[] bts = System.Text.Encoding.UTF8.GetBytes(json);
        // 文件寫入數(shù)據(jù)流
        file.Write(bts, 0, bts.Length);
        if (file != null)
        {
            //清空緩存
            file.Flush();
            // 關(guān)閉流
            file.Close();
            //銷毀資源
            file.Dispose();
        }
    }

    void ParseJSONLit()
    {
        //
        StreamReader reader = new StreamReader(Application.dataPath + "/Json/MyLitJsonByMono.txt");
        string str = reader.ReadToEnd();
        //print (str);
        reader.Close();
        reader.Dispose();
        //開始解析數(shù)據(jù)
        JsonData data = JsonMapper.ToObject(str);
        // 拿到JSON的對象
        print(data["StudentName"]);    //xioaming

        for (int i = 0; i < data["Messages"].Count; i++)
        {
            print(data["Messages"][i]["Subject"]);     //Chinese     Maths
        }
    }
}

litjson創(chuàng)建的json如下:


{
    "StudentName": "xioaming",
    "StudentGrade": 7,
    "StudentID": 122,
    "Messages": [{
        "Subject": "Chinese",
        "Stage": "First",
        "Score": "115",
        "Ranking": "6"
    }, {
        "Subject": "Maths",
        "Stage": "First",
        "Score": "119",
        "Ranking": "2"
    }]
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市杨幼,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖稳析,帶你破解...
    沈念sama閱讀 211,290評論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡影钉,警方通過查閱死者的電腦和手機(jī)夺谁,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,107評論 2 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來劳曹,“玉大人迫吐,你說我怎么就攤上這事熙宇。” “怎么了?”我有些...
    開封第一講書人閱讀 156,872評論 0 347
  • 文/不壞的土叔 我叫張陵颂郎,是天一觀的道長寺酪。 經(jīng)常有香客問我陨献,道長膜蛔,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,415評論 1 283
  • 正文 為了忘掉前任悍募,我火速辦了婚禮,結(jié)果婚禮上副砍,老公的妹妹穿的比我還像新娘豁翎。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,453評論 6 385
  • 文/花漫 我一把揭開白布熏版。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪灾杰。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,784評論 1 290
  • 那天栏渺,我揣著相機(jī)與錄音,去河邊找鬼。 笑死神僵,一個胖子當(dāng)著我的面吹牛责语,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播智末,決...
    沈念sama閱讀 38,927評論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼闽寡,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起土辩,我...
    開封第一講書人閱讀 37,691評論 0 266
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎结洼,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,137評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡莫换,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,472評論 2 326
  • 正文 我和宋清朗相戀三年喊暖,在試婚紗的時候發(fā)現(xiàn)自己被綠了风范。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片锌半。...
    茶點(diǎn)故事閱讀 38,622評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖遍膜,靈堂內(nèi)的尸體忽然破棺而出弛说,到底是詐尸還是另有隱情,我是刑警寧澤角塑,帶...
    沈念sama閱讀 34,289評論 4 329
  • 正文 年R本政府宣布窒朋,位于F島的核電站,受9級特大地震影響欺劳,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜淡诗,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,887評論 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望座掘。 院中可真熱鬧睛廊,春花似錦、人聲如沸蛾坯。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,741評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽脂矫。三九已至娄昆,卻和暖如春谷浅,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背掌猛。 一陣腳步聲響...
    開封第一講書人閱讀 31,977評論 1 265
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留孔飒,地道東北人园细。 一個月前我還...
    沈念sama閱讀 46,316評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親侣诵。 傳聞我的和親對象是個殘疾皇子蘸炸,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,490評論 2 348