using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ObjectPool : MonoBehaviour {
public static ObjectPool _instance;
public static Dictionary<string, ArrayList> Pool = new Dictionary<string, ArrayList>();
void Awake()
{
_instance = this;
}
public Object GetObject(string PrefabName,Vector3 position,Quaternion rotation,Transform Parent)//重对象池获取对象
{
string objectname = PrefabName + "Clone";
GameObject go = null;
if (Pool.ContainsKey(objectname) && Pool[objectname].Count > 0)
{
ArrayList list = Pool[objectname];
go = (GameObject)list[0];
list.Remove(0);
go.SetActive(true);
go.transform.parent = Parent;
go.transform.position = position;
go.transform.rotation = rotation;
}
else
{
go = Instantiate(Resources.Load(PrefabName), position, rotation) as GameObject;
go.transform.parent = Parent;
}
return go;
}
public static GameObject AddObject(GameObject g)
{
//获取gameobject的名字,会是一个在上面get方法里创建的(预设体的)gameobject,名字会是gameobject(Clone);
string key = g.name;
//如果字典里有这个key
if (Pool.ContainsKey(key))
{ //就在这个key所对应的数组中加入这个g (这个g就是已经用完的子弹,放到这个数组里的gameobjet都是不销毁只是取消激活等待再次利用的gameobject)
Pool[key].Add(g);
}
//如果没有这个key
else
{
//建立一个这个key的arraylist 并把g加进去
Pool[key] = new ArrayList() { g };
}
//不销毁而是取消激活
g.SetActive(false);
//返回g
return g;
}
}