HartoukChartEditor/Assets/Script/Manager/NotePoolManager.cs

132 lines
3.8 KiB
C#

using System.Collections.Generic;
using System.Diagnostics;
public class NotePoolManager : BasePool<BaseNote>
{
/// <summary>
/// 基于运行时数据用于存储生成出来活跃对象列表
/// </summary>
private Dictionary<RuntimeBaseNoteData, BaseNote> _dataToNoteCache = new Dictionary<RuntimeBaseNoteData, BaseNote>();
/// <summary>
/// 在每一个对象被创建出来的时候都会自动为其注册返回事件
/// </summary>
protected override void OnCreate(BaseNote obj)
{
obj.OnNoteUesd += ReturnBaseNoteToPool;
}
/// <summary>
/// 在激活新的对象的时候,将会在当前对象池中存储该对象的数据,用于快速查找
/// </summary>
protected override void OnGet(BaseNote obj)
{
base.OnGet(obj);
// 缓存映射关系
if (obj.SelfRef != null)
{
_dataToNoteCache.Add(obj.SelfRef, obj);
}
}
/// <summary>
/// 在对象被回收的时候,从活跃列表中移除该对象
/// </summary>
protected override void OnRelease(BaseNote obj)
{
base.OnRelease(obj);
// 清理缓存
if (obj.SelfRef != null && _dataToNoteCache.ContainsKey(obj.SelfRef))
{
_dataToNoteCache.Remove(obj.SelfRef);
}
}
/// <summary>
/// 泛型Note回收方法
/// </summary>
public void ReturnBaseNoteToPool(BaseNote note)
{
//如果字典中没有该类的对象池,则创建一个
var type = note.GetType();
if (!Pools.ContainsKey(type)) Pools[type] = new Stack<BaseNote>();
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);
}
}
}
/// <summary>
/// 使用运行时数据以近似遍历的方式在父对象池进行变量查找
/// </summary>
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;
}
/// <summary>
/// 在Note自己的字典集合中查询对象,查找失败将会返回Null,该方法仍在测试中
/// </summary>
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;
}
}