ScriptableObject
是一个用于生成单独Asset的结构。同时,它也能被称为是Unity中用于处理序列化的结构。
可以作为我们存储资源数据的有效方案。同时此资源可以作为我们AB包的有效资源!
ScriptableObject的特点:
- 不需要绑定到物体对象。
- 存放于编辑器或者作为一种资源存储。
- 操作方便,可视化动态修改。
- 读取数据方便,ScriptableObject已经是可序列化的数据。
- 可以在项目之间很好的复用而不会丢失数据。
注意的点
- 制作ScriptableObject,为了制作
ScriptableObject
,继承ScriptableObject
基类是首先要做的事情。这个时候,类名与Asset名必须要一样。另外,ScriptableObject
的限制和MonoBehaviour
是一样的。
- 实例化,通过
ScriptableObject.CreateInstance
来生成ScriptableObject
。使用new
操作符来生成是不行的。理由和MonoBehaviour
是一样的,Unity生成Object的时候必须经过序列化。
- 保存,实例化完成后是将Object作为Asset进行保存。通过
AssetDatabase.CreateAsset
就能够生成Asset。 Asset的后缀名必须是.asset。如果是其他后缀名的话,Unity会无法识别。
- GameObjectPoolList 继承自ScriptableObject,内容只有一个GameObjectPool类型的List,用于存储所有的池子
- using UnityEngine;
- using System.Collections;
- using System.Collections.Generic;
- public class GameObjectPoolList : ScriptableObject
- {
- //继承自ScriptableObject 表示把类GameObjectPoolList变成可以自定义资源配置的文件
- public List<GameObjectPool> poolList;
- }
- GameObjectPool 类是具体的池子,取对象的方法:遍历池子,找到第一个隐藏的对象将其可见并返回使用,找不到隐藏可用的对象时候就首先检查池子的对象数是否超过了最大容量,是的话就删除第一个对象,否则不作操作,接下来再创建一个新的游戏对象使用。
- using UnityEngine;
- using System.Collections;
- using System;
- using System.Collections.Generic;
- /// <summary>
- /// 资源池
- /// </summary>
- [Serializable]
- public class GameObjectPool {
- [SerializeField]
- public string name;
- [SerializeField]
- private GameObject prefab;
- [SerializeField]
- private int maxAmount;
- [NonSerialized]
- private List<GameObject> goList = new List<GameObject>();
- /// <summary>
- /// 表示从资源池中获取一个实例
- /// </summary>
- public GameObject GetInst()
- {
- foreach (GameObject go in goList)
- {
- if (go.activeInHierarchy == false)
- {
- go.SetActive(true);
- return go;
- }
- }
- if (goList.Count >= maxAmount)
- {
- GameObject.Destroy(goList[0]);
- goList.RemoveAt(0);
- }
- GameObject temp = GameObject.Instantiate(prefab) as GameObject;
- goList.Add(temp);
- return temp;
- }
- }
最后是拓展编辑器的内容以及保存Asset
- using UnityEngine;
- using System.Collections;
- using UnityEditor;
- public class PoolManagerEditor {
- [MenuItem("Manager/Crate GameObjectPoolConfig")]
- static void CreateGameObjectPoolList()
- {
- GameObjectPoolList poolList = ScriptableObject.CreateInstance<GameObjectPoolList>();
- string path = PoolManager.PoolConfigPath;
- AssetDatabase.CreateAsset(poolList,path);
- AssetDatabase.SaveAssets();
- }
- }


参考博客:https://blog.csdn.net/xdestiny110/article/details/79678922