5.18对象池
usingUnityEngine;
usingSystem.Collections;
usingSystem.Collections.Generic;
public classObjectPoolScript{
private GameObject poolObject;
private Dictionary<string,List<GameObject>>poolList=newDictionary<string,List<GameObject>>();
privateObjectPoolScript(){
}
private static ObjectPoolScript instance;
public static ObjectPoolScript Instance{
get{
if(instance==null){
instance=newObjectPoolScript();
}
return instance;
}
}
//对象池管理方法
//从对象池中取出物体
public GameObject GetGameObject(GameObject prefabs,
Vector3 position,Quaternion rotation){
string tag=prefabs.tag;
//判断对象池中是否存在当前预设体所对应的游戏物体的列表,并且该列表中是否存在物体,如果存在就取出,否则实例化该预设体的一个对象
if(poolList.ContainsKey(tag)&&poolList[tag].Count>0){
Debug.Log("sdf");
poolObject=poolList [tag] [0];
poolList[tag].Remove(poolObject);
poolObject.transform.position=position;
poolObject.transform.rotation=rotation;
poolObject.SetActive(true);
}else{
if(!poolList.ContainsKey(tag)){
poolList.Add(tag,newList<GameObject>( ));
}
poolObject=GameObject.Instantiate(prefabs,position,rotation)asGameObject;
}
return poolObject;
}
public void RecycleObject(GameObject obj){//对象池回收物体
if(poolList.ContainsKey(obj.tag)){
poolList [obj.tag].Add(obj);
obj.SetActive(false);
}
}
//销毁对象池中的物体
//public void RecycleObject(GameObject obj,bool isDestory,float delayTime){
//
//if(poolList.ContainsKey(obj.tag)){
//poolList[obj.tag].Add(obj);
//obj.SetActive(false);
//}
//}
}