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"
}]
}