NLDClient-yudde/ProjectNLD/Assets/Code/Scripts/Gameplay/Pool/ObjPoolManager.cs

70 lines
1.8 KiB
C#

using System;
using System.Collections.Generic;
using Gameplay.Pool.Debug;
namespace Gameplay.Pool
{
public class ObjPoolManager
{
private static ObjPoolManager _instance;
public static ObjPoolManager instance
{
get
{
if (_instance == null)
{
_instance = new ObjPoolManager();
#if UNITY_EDITOR
CmpPoolManager.CreateInstance();
#endif
}
return _instance;
}
}
internal readonly Dictionary<Type, ObjPool> poolDict = new Dictionary<Type, ObjPool>();
public T Get<T>() where T : class, IPoolData, new()
{
var type = typeof(T);
if (poolDict.TryGetValue(type, out var objPool))
{
if (objPool.Get() is T getResult)
{
getResult.OnGet();
return getResult;
}
}
DebugUtil.LogWarning("type:" + type + " not in poolDict, return new T");
return new T();
}
private void _ReutrnByType(Type type,
object obj)
{
if (poolDict.TryGetValue(type, out var objPool))
{
var pool = objPool;
pool.Return(obj);
}
else
{
var newObjPool = new ObjPool();
newObjPool.Return(obj);
poolDict.Add(type, newObjPool);
}
}
public void Return<T>(T obj) where T: IPoolData
{
var type = obj.GetType();
obj.OnReturn();
_ReutrnByType(type, obj);
}
public void Clear()
{
poolDict.Clear();
}
}
}