解耦代码
public class ObjectPool
{
private static ObjectPool instance;
private Dictionary<string, Queue<GameObject>> objectPool = new Dictionary<string, Queue<GameObject>>();
private GameObject pool;
public static ObjectPool Instance
{
get
{
if (instance == null)
{
instance = new ObjectPool();
}
return instance;
}
}
public void InitDic()
{
objectPool.Clear();
}
public GameObject GetObject(GameObject prefab)
{
GameObject _object;
if (!objectPool.ContainsKey(prefab.name) || objectPool[prefab.name].Count == 0)
{
_object = GameObject.Instantiate(prefab);
PushObject(_object);
if (pool == null)
pool = new GameObject("ObjectPool");
GameObject child = GameObject.Find(prefab.name);
if (!child)
{
child = new GameObject(prefab.name);
child.transform.SetParent(pool.transform);
}
_object.transform.SetParent(child.transform);
}
_object = objectPool[prefab.name].Dequeue();
_object.SetActive(true);
return _object;
}
public void PushObject(GameObject prefab)
{
string _name = prefab.name.Replace("(Clone)", string.Empty);
if (!objectPool.ContainsKey(_name))
objectPool.Add(_name, new Queue<GameObject>());
objectPool[_name].Enqueue(prefab);
prefab.SetActive(false);
}
}
- 当我们使用这个代码时,要注意预制体prefab的名字不能是Hierarchy里面已经有的名字。因为如果你的prefab的名字与其相同,那么,当你生成prefab时,这个prefab克隆会变成这个同名的子物体。而不会出现在ObjectPool里面。
- 所有用对象池生成的prefab,都要将代码中的初始化放到enable里,而不是start里。因为每次从对象池调出时,enable会再次执行,而start不会。
|