數據持久化
談到數據持久化,在Unity的游戲開發中十分重要的,不管是是在本地和服務器端,數據持久化都是我們學習的難點,數據持久化的技術有很多種,這里只選取幾種,目前也是我所學到的,在接下來的時間里會陸續整理到這里。
Part1:PlayerPrefs類
這是unity聖典中給出的,
PlayerPrefs 游戲存檔 Description 描述 在游戲會話中儲存和訪問游戲存檔。這個是持久化數據儲存,比如保存游戲記錄。 Editor/Standalone 編輯器 / 桌面平台 Mac OS 在Mac OS X上PlayerPrefs是存儲在~/Library/Preferences文件夾,名為unity.[company name].[product name].plist,其中company name和product name名是在Project Setting中設置,.plist文件可用於編輯器和桌面平台運行。 (打開Find,按住Option鍵,點擊“前往 →“資源庫”,就可以找到Preferences文件夾。) Windows 在Windows平台下,PlayerPrefs被存儲在注冊表的 HKEY_CURRENT_USER\Software\[company name]\[product name]鍵下(打開“運行”輸入regedit打開注冊表),其中company name和product name名是在Project Setting中設置。 Linux 在Linux,PlayerPrefs是儲存在~/.config/unity3d/[CompanyName]/[ProductName]。其中CompanyName和ProductName名是在Project Setting中設置 Windows Store 在Windows Store,PlayerPrefs是儲存在%userprofile%\AppData\Local\Packages\[ProductPackageId]>\LocalState\playerprefs.dat。 Windows Phone 在Windows Phone 8,PlayerPrefs是儲存在應用自己的文件夾,參見:Windows.Directory.localFolder WebPlayer 網頁 在網頁平台,PlayerPrefs是儲存在二進制文件,看下面的對應的各平台位置: Mac OS X: ~/Library/Preferences/Unity/WebPlayerPrefs Windows: %APPDATA%\Unity\WebPlayerPrefs 一個游戲存檔文件對應一個web播放器URL並且文件大小被限制為1MB。如果超出這個限制,SetInt、SetFloat和SetString將不會存儲值並拋出一個PlayerPrefsException異常。 Static Functions 靜態函數 DeleteAll Removes all keys and values from the preferences. Use with caution. 從游戲存檔中刪除所有key。請謹慎使用。 DeleteKey Removes key and its corresponding value from the preferences. 從游戲存檔中刪除key和它對應的值。 GetFloat Returns the value corresponding to key in the preference file if it exists. 如果存在,返回游戲存檔文件中key對應的浮點數值。 GetInt Returns the value corresponding to key in the preference file if it exists. 如果存在,返回游戲存檔文件中key對應的整數值。 GetString Returns the value corresponding to key in the preference file if it exists. 如果存在,返回游戲存檔文件中key對應的字符串值。 HasKey Returns true if key exists in the preferences. 如果key在游戲存檔中存在,返回true。 Save Writes all modified preferences to disk. 寫入所有修改參數到硬盤。 SetFloat Sets the value of the preference identified by key. 設置由key確定的浮點數值。 SetInt Sets the value of the preference identified by key. 設置由key鍵確定的整數值。 SetString Sets the value of the preference identified by key. 設置由key確定的字符串值。
下面我通過寫的一小段代碼呈現一下怎么使用:
public class Person { /// <summary> /// 用於存儲名字 /// </summary> private string name; /// <summary> /// 運用屬性的特征去存儲一個變量到PlayerPrefs中,數據持久化 /// </summary> /// <value>The name.</value> public string Name { get{ return PlayerPrefs.GetString ("Name"); } set{ PlayerPrefs.SetString ("Name", value); PlayerPrefs.Save (); } } /// <summary> /// 返回年齡 /// </summary> private int age; public int Age{ get{ return PlayerPrefs.GetInt ("Age"); } set{ PlayerPrefs.SetInt ("Age", value); PlayerPrefs.Save (); } } /// <summary> /// 無參數的構造函數 /// </summary> public Person() { } /// <summary> /// 有參數的構造函數 /// </summary> /// <param name="_name">Name.</param> /// <param name="_age">Age.</param> public Person(string _name,int _age) { this.Name = _name; this.Age = _age; } public override string ToString () { return string.Format ("[Person: Name={0}, Age={1}]", Name, Age); } }
將數據存儲到屬性中,也是一個不錯的方法。這里需要注意的是設置了值后,調用Save()方法。
Part2:Json數據持久化
首先需要用到一個json的動態鏈接庫,JsonFx,網上可以找到,這里給出一個百度盤的連接鏈接: https://pan.baidu.com/s/1kVmc4Qz 密碼: kqg2
然后就是把這個動態鏈接庫導入到我們的工程的Plugins目錄下面,引用即可。以下是代碼部分
這個是要用json 轉化的目標類,
using System.Collections; using System.Collections.Generic; public class Body { public string name; public int age; public Body() { } public Body(string _name,int _age) { this.name = _name; this.age = _age; } public override string ToString () { return string.Format ("[Body:name:{0},age:{1}]",name,age); } }
下面這個類是用於轉化的的測試類:
using System.Collections; using System.Collections.Generic; using UnityEngine; using JsonFx.Json; using System.IO; public class TestJson : MonoBehaviour { /// <summary> /// 靜態字段保存路徑 /// </summary> static string pathdata="/data.txt"; void Start() { Debug.Log(Application.dataPath); Write (); Read (); } /// <summary> /// 寫入json數據,將類序列化 /// </summary> public static void Write() { Body body=new Body ("zhangsan",25); string text = JsonWriter.Serialize (body); File.WriteAllText (DataPathTest.GetDataPath ()+pathdata, text); } /// <summary> /// 將文本反序列化為一個類 /// </summary> public static void Read() { string str = File.ReadAllText (DataPathTest.GetDataPath () +pathdata); Body bd = JsonReader.Deserialize<Body> (str); Debug.Log (bd.ToString()); } }
下面這個只是寫個類用於獲取路徑,(有點多余)
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DataPathTest { public static string GetDataPath() { if (Application.platform == RuntimePlatform.IPhonePlayer) { string path = Application.dataPath.Substring (0, Application.dataPath.Length - 5); return path + "/Dcoument"; } else if (Application.platform == RuntimePlatform.Android) { return Application.persistentDataPath + "/"; } else { return Application.dataPath; } } }
最后補充一個易錯的點,就是我起先在用JsonFx轉化的時候出現的一些問題,先將body 對象轉化為json 字符串,讓后在轉化為body的過程中出現的報錯,后來百度找到了原因,具體可以參考這篇文章:http://www.cnblogs.com/zhuhongjongy/p/4974473.html
今天就寫到這里,
待續。。。。