Unity 使用JSON實現本地資料儲存和讀取
阿新 • • 發佈:2019-02-18
通過鍵值對的方式對遊戲物件資訊進行儲存和讀取,,,下面以一個人物物件為例,
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LitJson;
using System.IO;
using UnityEditor;
public class Person
{
public string Name { get; set; }
public double HP { get; set; }
public int Level { get; set; }
public double Exp { get; set; }
public int Attak { get; set; }
}
public class PersonList
{
public Dictionary<string, string> dictionary = new Dictionary<string, string>();
}
public class Classtext : MonoBehaviour {
/*定義一個Person物件(其屬性包括,Name,HP,Level,Exp,Attak等),
將其轉會成json格式字串並且寫入到person.json的文字中,
然後將person.json文字中的內容讀取出來賦值給新的Person物件。
*/
public PersonList personList = new PersonList();
// Use this for initialization
void Start () {
//初始化人物資訊
Person person = new Person();
person.Name = "Czhenya";
person.HP = 100;
person.Level = 30;
person.Exp = 999.99;
person.Attak = 38;
//呼叫儲存方法
Save(person);
}
/// <summary>
/// 儲存JSON資料到本地的方法
/// </summary>
/// <param name="player">要儲存的物件</param>
public void Save(Person player)
{
//打包後Resources資料夾不能儲存檔案,如需打包後使用自行更換目錄
string filePath = Application.dataPath + @"/Resources/JsonPerson.json";
Debug.Log(Application.dataPath + @"/Resources/JsonPerson.json");
if (!File.Exists(filePath)) //不存在就建立鍵值對
{
personList.dictionary.Add("Name", player.Name);
personList.dictionary.Add("HP", player.HP.ToString());
personList.dictionary.Add("Level", player.Level.ToString());
personList.dictionary.Add("Exp", player.Exp.ToString());
personList.dictionary.Add("Attak", player.Attak.ToString());
}
else //若存在就更新值
{
personList.dictionary["Name"] = player.Name;
personList.dictionary["HP"] = player.HP.ToString();
personList.dictionary["Level"] = player.Level.ToString();
personList.dictionary["Exp"] = player.Exp.ToString();
personList.dictionary["Attak"] = player.Attak.ToString();
}
//找到當前路徑
FileInfo file = new FileInfo(filePath);
//判斷有沒有檔案,有則開啟檔案,,沒有建立後開啟檔案
StreamWriter sw = file.CreateText();
//ToJson介面將你的列表類傳進去,,並自動轉換為string型別
string json = JsonMapper.ToJson(personList.dictionary);
//將轉換好的字串存進檔案,
sw.WriteLine(json);
//注意釋放資源
sw.Close();
sw.Dispose();
AssetDatabase.Refresh();
}
/// <summary>
/// 讀取儲存資料的方法
/// </summary>
public void LoadPerson()
{
//除錯用的 //Debug.Log(1);
//TextAsset該類是用來讀取配置檔案的
TextAsset asset = Resources.Load("JsonPerson") as TextAsset;
if (!asset) //讀不到就退出此方法
return;
string strdata = asset.text;
JsonData jsdata3 = JsonMapper.ToObject(strdata);
//在這裡迴圈輸出表示讀到了資料,,即此資料可以使用了
for (int i = 0; i < jsdata3.Count; i++)
{
Debug.Log(jsdata3[i]);
}
//使用foreach輸出的話會以[鍵,值],,,
/*foreach (var item in jsdata3)
{
Debug.Log(item);
}*/
}
private void OnGUI()
{ //點選讀取儲存的檔案
if (GUILayout.Button("LoadTXT"))
{
LoadPerson();
}
}
}
注:這個程式碼,釋出之後執行儲存資料儲存不上,是儲存路徑的問題,Resources屬於Unity中的特殊資料夾:打包後不能儲存檔案,,,關於特殊資料夾的簡介:http://blog.csdn.net/czhenya/article/details/78095273,,,童鞋們注意一下這個問題,,感謝一樓童鞋的糾錯,
效果圖: