using System.Collections.Generic; using System.Linq; using UnityEngine; namespace Game { public delegate void PoolItemInitHandler(TItem item); public class ObjectPoolItemBase : MetaDataHandler { public bool IsAlive; public void Create() { if (IsAlive) return; IsAlive = true; OnCreate(); CreateBind(); } public void Destroy() { if (!IsAlive) return; IsAlive = false; OnDestroy(); ClearBind(); } protected virtual void OnCreate() { } protected virtual void OnDestroy() { } } public class ObjectPoolBase : ManagerBase where TManager : new() { public GameObject Root; protected Dictionary> ObjectPool; public override void OnInit() { ObjectPool = new Dictionary>(); CreateRoot(typeof(TManager).Name); } private void CreateRoot(string rootName) { Root = new GameObject(rootName); Object.DontDestroyOnLoad(Root); } protected T Create(object objType, PoolItemInitHandler callback) where T : ObjectPoolItemBase, new() { var pool = EnSureGetPool(objType); foreach (var obj in from obj in pool where !obj.IsAlive select obj as T) { obj.Create(); return obj; } var newObj = new T(); pool.Add(newObj); callback?.Invoke(newObj); newObj.Create(); return newObj; } protected void PreCreate(object objType, PoolItemInitHandler callback, int num) where T : ObjectPoolItemBase, new() { var pool = EnSureGetPool(objType); for (var _ = 0; _ < num; _++) { var newObj = Create(objType, callback); newObj.Destroy(); } } protected List EnSureGetPool(object objType) { if (!ObjectPool.ContainsKey(objType)) ObjectPool[objType] = new List(); return ObjectPool[objType]; } } }