Unity編輯器擴展 Chapter7--使用ScriptableObject持久化存儲數據
Unity編輯器擴展 Chapter7--使用ScriptableObject持久化存儲數據
OverView
API
ScriptableObject是unity中的一種特別的類型,它不需要掛在場景中的對象上。它可以視作asset資源一樣,存儲在項目文件中。在一些特殊的情況下要比JSON,XML及TXT方式來存儲持久化數據要受益得多。因為unity可以自主序列化和解析該類型,而不需要像其他方式一樣需要第三方工具或自己編寫解析工具。
注意:它仍然有Awake,OnEnable,OnDestory等方法可以供你使用,詳見上方API
創建一個ScriptableObject
需要創建一個ScriptableObject只需要讓一個類繼承ScriptableObject即可。
using UnityEngine;
using System;
namespace MyScirptableObject {
[Serializable]
public class LevelSettings : ScriptableObject {
public float gravity = -30;
public AudioClip bgm;
public Sprite background;
}
}
創建一個包含該數據類的asset資源
可以通過多種方式來創建該資源,主要使用 ScriptableObject.CreateInstance 方法
方式一:使用tool菜單創建
注意:在使用Editor類中添加如下方法
public static T CreateAsset<T>(string path)
where T : ScriptableObject {
T dataClass = (T) ScriptableObject.CreateInstance<T>();
AssetDatabase.CreateAsset(dataClass, path);
AssetDatabase.Refresh();
AssetDatabase.SaveAssets();
return dataClass;
}
[MenuItem ("Tools/Level Creator/New Level Settings")]
private static void NewLevelSettings () {
string path = EditorUtility.SaveFilePanelInProject(
"New Level Settings",
"LevelSettings",
"asset",
"Define the name for the LevelSettings asset");
if(path != "") {
EditorUtils.CreateAsset<LevelSettings>(path);
}
}
效果:

Menu
方式二:右鍵Project面板使用Create菜單創建
using UnityEngine;
using UnityEngine.Events;
[CreateAssetMenu(menuName= "CreateMyScriptableScript",fileName= "Scripts/MyScriptableScript")]
public class MyScriptableScript : ScriptableObject
{
public string Name;
public int Level;
public GameObject Prefab;
public UnityEvent Event;
public void Instance() {
GameObject go = GameObject.Instantiate(Prefab);
go.name = Name;
Event.AddListener(() =>
{
Debug.Log(("call event!"));
foreach (var renderer in go.transform.GetChild(0).GetComponentsInChildren<Renderer>())
{
renderer.material.color = Color.red;
}
});
Event.Invoke();
}
}
效果:

Create
創建后我們就可以在Inspector面板中在為該asset添加數據

DataAsset
使用ScirptableObject存儲的數據
直接在使用的類中聲明需要的ScriptableObject類型即可。然后就可以將之前創建好的asset資源添加到上面,我們就可以使用該方式存儲的數據了。

Use