游戲中保存數(shù)據(jù)的途徑
- PlayerPrefs
- csv, xml, json等配置文件
- Scriptable序列化
PlayerPrefs與配置文件的缺點(diǎn)
- PlayerPrefs只能在運(yùn)行時保存讀取一些臨時數(shù)據(jù)
- 配置文件袁翁,需要加載進(jìn)來后解析為具體的數(shù)據(jù)對象又活,然后學(xué)要在代碼中獲取對應(yīng)的數(shù)據(jù)對象
Scriptable優(yōu)點(diǎn)
- 可以直接將對象序列化到本地刑峡,以asset的方式存儲
- 可以在Inspector窗口預(yù)覽編輯asset
- 通過拖拽直接被Monobehaviour引用像屋,不用手動加載
- 自動解析為對象
- 但如果將asset打包成assetbundle岸夯,則需要在代碼中手動加載,不可以直接通過拖拽來引用了
實例
定義可序列化類
public class TestScriptable : ScriptableObject
{
public int id;
public List<MyClass> lst;
}
// Scriptable引用到的類痢甘,要聲明為Serializable
[Serializable]
public class MyClass
{
}
生成本地Scriptable asset
[MenuItem("Assets/Create/CreateSO")]
public static void CreateSO()
{
TestScriptable s = ScriptableObject.CreateInstance<TestScriptable>();
AssetDatabase.CreateAsset(s, "Assets/Resources/test.asset");
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
使用AssetDatabase加載
TestScriptable ts = AssetDatabase.LoadAssetAtPath("Assets/Resources/test.asset", typeof(ScriptableObject)) as TestScriptable;
Debug.Log(ts.id);
使用Resource加載
TestScriptable ts = Resources.Load("test") as TestScriptable;
Debug.Log(ts.id);
使用www加載
IEnumerator Start ()
{
WWW www = new WWW("file://" + Application.dataPath + "/test.assetbundle");
yield return www;
TestScriptable ts = www.assetBundle.mainAsset as TestScriptable;
Debug.Log(ts.id);
}
https://docs.unity3d.com/560/Documentation/Manual/class-ScriptableObject.html