ScriptableObject非常适合小数量的游戏数值。
使用ScriptableObject的时候需要注意,生成ScriptableObject数据文件需要自己写Editor代码实现。
大概的工作流程是:写一个ScriptableObject(继承ScriptableObject的类,相当于数据模板) → 使用自己写的Editor代码生成一个实现该模板的数据文件 → Inspector面板中编辑数据。
给出我的Editor代码:
using UnityEngine; using System.IO; using System.Collections; using UnityEditor; public class Scriptablity : MonoBehaviour { public static T Create<T> ( string _path, string _name) where T : ScriptableObject { if ( new DirectoryInfo(_path).Exists == false ) { Debug.LogError ( "can't create asset, path not found" ); return null; } if ( string.IsNullOrEmpty(_name) ) { Debug.LogError ( "can't create asset, the name is empty" ); return null; } string assetPath = Path.Combine( _path, _name + ".asset" ); T newT = ScriptableObject.CreateInstance<T>(); AssetDatabase.CreateAsset(newT, assetPath); Selection.activeObject = newT; return newT; } public static void Create<T>() where T : ScriptableObject { string assetName = "New " + typeof(T).Name; string assetPath = "Assets"; if(Selection.activeObject) { assetPath = AssetDatabase.GetAssetPath(Selection.activeObject); if (Path.GetExtension(assetPath) != "") { assetPath = Path.GetDirectoryName(assetPath); } } bool doCreate = true; string path = Path.Combine( assetPath, assetName + ".asset" ); FileInfo fileInfo = new FileInfo(path); if ( fileInfo.Exists ) { doCreate = EditorUtility.DisplayDialog( assetName + " already exists.", "Do you want to overwrite the old one?", "Yes", "No" ); } if ( doCreate ) { T T_info = Create<T> ( assetPath, assetName ); Selection.activeObject = T_info; } } public static void Create() { Debug.LogError("You should call 'Create' method like this : Create<ExampleData>();"); } }
使用方法:
1.写个ScriptableObject。
public class Example : ScriptableObject { public int id; public string name; }
2.写个MonoBehavior调用Create方法生成Example格式的数据。
public class ExampleItem: MonoBehaviour { [MenuItem("Example/Create/Example Data")] static void CreatExample() { Scriptablity.Create<Example>(); } }
3.在Inspector面板编辑数据。
4.使用该数据
public class ExampleUsage : MonoBehavior { public Example exampleInfo; void Start() { Debug.Log(exampleInfo.name); } }