缓存池模块
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 缓存池模块
/// 1.Dictionary List
/// 2.GameObject Resources
/// </summary>
public class PoolMgr : BaseManager<PoolMgr>
{
public Dictionary<string, List<GameObject>> poolDic = new Dictionary<string, List<GameObject>>();
public GameObject GetObj(string name)
{
GameObject obj = null;
if (poolDic.ContainsKey(name) && poolDic[name].Count > 0)
{
obj = poolDic[name][0];
poolDic[name].RemoveAt(0);
}
else
{
obj = GameObject.Instantiate(Resources.Load<GameObject>(name));
obj.name = name;
}
obj.GetOrAddComponent<DelayPush>();
obj.SetActive(true);
return obj;
}
public void PushObj(string name, GameObject obj)
{
obj.SetActive(false);
if (poolDic.ContainsKey(name))
{
poolDic[name].Add(obj);
}
else
{
poolDic.Add(name, new List<GameObject>() { obj });
}
}
}
测试
加载
void Update()
{
if (Input.GetMouseButtonDown(0))
{
PoolMgr.GetInstance().GetObj("Cube");
}
if (Input.GetMouseButtonDown(1))
{
PoolMgr.GetInstance().GetObj("Sphere");
}
}
回收
private void OnEnable()
{
Invoke(nameof(Push), 1f);
}
void Push()
{
PoolMgr.GetInstance().PushObj(this.gameObject.name, this.gameObject);
}
拓展
GetOrAddComponent的实现
using UnityEngine;
static public class MethodExtensionForUnity
{
/// <summary>
/// Gets or add a component. Usage example:
/// BoxCollider boxCollider = transform.GetOrAddComponent<BoxCollider>();
/// </summary>
static public T GetOrAddComponent<T>(this Component child, bool set_enable = false) where T : Component
{
T result = child.GetComponent<T>();
if (result == null)
{
result = child.gameObject.AddComponent<T>();
}
var bcomp = result as Behaviour;
if (set_enable)
{
if (bcomp != null) bcomp.enabled = true;
}
return result;
}
static public T GetOrAddComponent<T>(this GameObject go) where T : Component
{
T result = go.transform.GetComponent<T>();
if (result == null)
{
result = go.AddComponent<T>();
}
var bcomp = result as Behaviour;
if (bcomp != null) bcomp.enabled = true;
return result;
}
public static void walk(this GameObject o, System.Action<GameObject> f)
{
f(o);
int numChildren = o.transform.childCount;
for (int i = 0; i < numChildren; ++i)
{
walk(o.transform.GetChild(i).gameObject, f);
}
}
}