經過定製資源配置文件來管理數據編輯器
即:把全部可序列化的數據容器類放入自定義資源文件中,該資源文件能夠在Inspector視圖中進行配置,Unity會自動進行序列化、反序列化來讀取、保存這些數據在該資源文件中。工具
使用定製資源配置文件與使用XML、JSON或者其餘一些外部文件格式相比有不少好處:code
數據容器類將成爲資源配置文件的基本數據項,並可在Inspector面板中顯示、修改這些數據(序列化與反序列化)
如GameObjectPoolElement.csip
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; [Serializable] public class Enemy { public string Name; public int Capacity; public GameObject Prefab; [NonSerialized] private List<GameObject> goList = new List<GameObject>(); } GameObjectPoolElement的管理類,GameObjectPool.cs using UnityEngine; using System.Collections.Generic; public class GameObjectPool : ScriptableObject { public List<GameObjectPoolElement> GOPoolElement; }
用於建立定製資源配置文件的工具方法容器類:CustomAssetUtility.cs
注意:資源配置文件必須以.asset爲擴展名,不然編輯器沒法識別ci
using UnityEngine; using UnityEditor; using System.IO; public class CustomAssetUtility { //建立一個指定類型的定製資源配置文件 public static void CreateAsset<T>() where T : ScriptableObject { T asset = ScriptableObject.CreateInstance<T>(); string path = AssetDatabase.GetAssetPath(Selection.activeObject); if (path==string.Empty) { path = "Assets"; } else if (Path.GetExtension(path)!=string.Empty) //若是擴展名不爲空 { path = path.Replace(Path.GetFileName(AssetDatabase.GetAssetPath(Selection.activeObject)), string.Empty); } //存放路徑+文件全名,把生成的資源文件放於Resources文件夾是爲了打包後進行壓縮,使用時便於讀取,但也能夠放在其它地方 string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath(path + "/Resources/ " + typeof(T).ToString() + ".asset"); AssetDatabase.CreateAsset(asset, assetPathAndName); AssetDatabase.SaveAssets(); EditorUtility.FocusProjectWindow(); Selection.activeObject = asset; } }
擴展編輯器類:CreatMenu.cs資源
using UnityEngine; using UnityEditor; using System; using System.Collections.Generic; public class CreatMenu { [MenuItem("MyTools/CreateAssets/GameObjectPool")] public static void CreateAsset() { CustomAssetUtility.CreateAsset<GameObjectPool>(); } }
1.點擊編輯器主菜單上的MyTools/CreateAssets/GameObjectPool來建立一個定製資源配置文件。
2.在Inspector面板中能夠對它進行配置修改,任何改動都會被自動保存到該文件中(Unity會自動執行序列化操做來保存)。
3.定製資源配置文件如今成爲了一個資源文件,能夠像使用其它資源文件同樣使用它。
如:把該文件直接賦值給GameObjectPool類型的變量,如:string
using UnityEngine; using System.Collections.Generic; public class test : MonoBehaviour { //方式1:直接拖拽賦值 //public GameObjectPool goPool1; //方式2:代碼讀取資源 private GameObjectPool goPool2; void Awake() { goPool2 = Resources.Load<GameObjectPool>("GameObjectPool"); } void Start() { List<GameObjectPoolElement> goPoolElementList = goPool2.GOPoolElement; Debug.Log(goPoolElementList[0].Name); Debug.Log(goPoolElementList[0].Capacity); Debug.Log(goPoolElementList[0].Prefab); } }