对象池是Unity中经常会用到的一种减少内存开销的服务,可用于减少大量的对象创建和销毁带来的内存开销。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectsPool : MonoBehaviour {
private static ObjectsPool instance;
private ObjectsPool()
{
pool = new Dictionary<string, List<GameObject>>();
prefabs = new Dictionary<string,GameObject>();
}
public static ObjectsPool GetInstance()
{
if(instance == null)
{
instance = new ObjectsPool();
}
return instance;
}
private Dictionary<string, List<GameObject>> pool;
private Dictionary<string, GameObject> prefabs;
public GameObject GetObj(string name)
{
GameObject result = null;
//判断是否有对象池
if(pool.ContainsKey(name))
{
//判断是否对象池中有对象
if(pool[name].Count > 0)
{
result = pool[name][0];
result.SetActive(true);
pool[name].Remove(result);
return result;
}
}
//如果没有该名字的对象池或者该名字对象池没有对象
GameObject prefab = null;
//如果已经加载过该prefab
if(prefabs.ContainsKey(name))
{
prefab = prefabs[name];
}
else
{
prefab = Resources.Load<GameObject>("Prefabs/" + name);
prefabs.Add(name, prefab);
}
result = UnityEngine.Object.Instantiate(prefab);
result.name = name;
return result;
}
/// <summary>
/// 回收对象到对象池
/// </summary>
/// <param name="objName"></param>
public void RecycleObj(GameObject obj)
{
//设置为非激活
obj.SetActive(false);
//判断是否有该对象的对象池
if (pool.ContainsKey(obj.name))
{
//放置到该对象池
pool[obj.name].Add(obj);
}
else
{
//创建该类型的池子,并将对象放入
pool.Add(obj.name, new List<GameObject>() { obj });
}
}
}