using System.Collections.Generic; using System.Diagnostics; public class NotePoolManager : BasePool { /// /// 基于运行时数据用于存储生成出来活跃对象列表 /// private Dictionary _dataToNoteCache = new Dictionary(); /// /// 在每一个对象被创建出来的时候都会自动为其注册返回事件 /// protected override void OnCreate(BaseNote obj) { obj.OnNoteUesd += ReturnBaseNoteToPool; } /// /// 在激活新的对象的时候,将会在当前对象池中存储该对象的数据,用于快速查找 /// protected override void OnGet(BaseNote obj) { base.OnGet(obj); // 缓存映射关系 if (obj.SelfRef != null) { _dataToNoteCache.Add(obj.SelfRef, obj); } } /// /// 在对象被回收的时候,从活跃列表中移除该对象 /// protected override void OnRelease(BaseNote obj) { base.OnRelease(obj); // 清理缓存 if (obj.SelfRef != null && _dataToNoteCache.ContainsKey(obj.SelfRef)) { _dataToNoteCache.Remove(obj.SelfRef); } } /// /// 泛型Note回收方法 /// public void ReturnBaseNoteToPool(BaseNote note) { //如果字典中没有该类的对象池,则创建一个 var type = note.GetType(); if (!Pools.ContainsKey(type)) Pools[type] = new Stack(); Pools[type].Push(note); note.gameObject.SetActive(false); } public override void ClearPool() { foreach (var list in ActiveObjectList) { foreach (var note in list.Value) { ReturnBaseNoteToPool(note); } } } /// /// 使用运行时数据以近似遍历的方式在父对象池进行变量查找 /// public BaseNote GetNoteByRuntimeData(RuntimeBaseNoteData data) { if (data == null) { UnityEngine.Debug.LogError("NotePoolManager" + "传入的数据是Null"); return null; } BaseNote note = null; switch (data) { case RuntimeTapData: { ForEach((TapController n) => { if (n.SelfRef == data) note = n; }); break; } case RuntimeDragData: { ForEach((DragController n) => { if (n.SelfRef == data) note = n; }); break; } case RuntimeFlickData: { ForEach((FlickController n) => { if (n.SelfRef == data) note = n; }); break; } case RuntimeSnakeData: { ForEach((DataFlowController n) => { if (n.SelfRef == data) note = n; }); break; } } UnityEngine.Debug.LogError("NotePoolManager" + ":这个运行时数据不在对象池的键中,没有找到对应的视图对象"); return note; } /// /// 在Note自己的字典集合中查询对象,查找失败将会返回Null,该方法仍在测试中 /// public BaseNote GetNoteByRuntimeDataInPool(RuntimeBaseNoteData data) { if (data == null) { UnityEngine.Debug.LogError("NotePoolManager" + ":传入的数据是Null"); return null; } if (_dataToNoteCache.TryGetValue(data, out BaseNote result)) { return result; } return null; } }