using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; /// /// 对象池 /// /// public class ObjectPool where T : Object { List activedObjects = new List(); List objectsPool = new List(); T prefab; UnityAction onTakeOutOneObject; UnityAction onPutInOneObject; /// /// /// /// 用于实例化的预设体 /// 拿出一个实例的回调 /// 放入一个实例的回调 public ObjectPool(T prefab, UnityAction onTakeOutOneObj = null, UnityAction onPutInOneObj = null) { this.prefab = prefab; this.onTakeOutOneObject = onTakeOutOneObj; this.onPutInOneObject = onPutInOneObj; } /// /// 拿出一个对象 /// /// public T TakeOutOneObject() { return TakeOutOneObject(null); } /// /// 拿出一个对象并设置父物体 /// /// 父物体 /// public T TakeOutOneObject(Transform parent) { T obj; if (objectsPool.Count > 0) { obj = objectsPool[0]; objectsPool.RemoveAt(0); } else { obj = InstantiateObject(parent); } activedObjects.Add(obj); if (onTakeOutOneObject != null) { onTakeOutOneObject(obj); } return obj; } public void PutInObject(T obj) { if (activedObjects.Contains(obj)) { activedObjects.Remove(obj); objectsPool.Add(obj); if (onPutInOneObject != null) { onPutInOneObject(obj); } } } public void ClearAllActivedObjects() { while (activedObjects.Count > 0) { PutInObject(activedObjects[0]); } } public T[] GetActivedObjects() { return activedObjects.ToArray(); } T InstantiateObject(Transform parent) { if (parent != null) { return Object.Instantiate(prefab, parent); } return Object.Instantiate(prefab); } }