经过定制资源配置文件来管理数据编辑器
即:把全部可序列化的数据容器类放入自定义资源文件中,该资源文件能够在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); } }