Unity对象池封装
1、设计思路:
将打算销毁的对象设置为不可见并保存在对象池【字典+列表】,重新生成对象的时候直接从对象池中取出显示即可。
2、具体实现:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PoolManager : SingletonBase<PoolManager>
{
public GameObject Pool;
public GameObject ResPool;
private Dictionary<string, List<GameObject>> PoolDict = new Dictionary<string, List<GameObject>>();
public PoolManager()
{
Pool = new GameObject("Pool");
ResPool = new GameObject("ResPool");
ResPool.transform.parent = Pool.transform;
GameObject.DontDestroyOnLoad(Pool);
}
/// <summary>
/// 放置物体至 对象池
/// </summary>
public void PutObj(string name, GameObject obj)
{
obj.SetActive(false);
if (PoolDict.ContainsKey(name))
{
PoolDict[name].Add(obj);
}
else
{
PoolDict.Add(name, new List<GameObject>() { obj });
}
obj.transform.SetParent(ResPool.transform);
}
/// <summary>
/// 从对象池里取出 对象
/// </summary>
/// <returns></returns>
public GameObject GetObj(string name)
{
GameObject obj = null;
if (PoolDict.ContainsKey(name) && PoolDict[name].Count > 0)
{
obj = PoolDict[name][0];
PoolDict[name].RemoveAt(0);
}
else
{
obj = GameObject.Instantiate(Resources.Load<GameObject>(name));
obj.name = name;
}
obj.transform.SetParent(Pool.transform);
obj.SetActive(true);
return obj;
}
}
对象挂载脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class pushObj : MonoBehaviour {
void OnEnable()
{
Invoke("DestoryObj", 3);
}
private void DestoryObj()
{
PoolManager.getInstance().PutObj(this.gameObject.name,this.gameObject);
}
}
使用:
PoolManager.getInstance().GetObj("Cube1");