之前做小游戏整的,方便使用,存一下
代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Poolmanagement : MonoBehaviour
{
private Dictionary<string, Pool> manapool; //字典,各种对象池的总结整理
//public GameObject gamepool;
public static Poolmanagement instance; //单例
// Use this for initialization
public Poolmanagement()
{
manapool = new Dictionary<string, Pool>(); 初始化
}
private void Awake()
{
instance = this; //单例模式
}
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public T CreatGameObjectPool<T>(string poolName) where T : Pool, new()//这个函数用来新创建对象池。
{
if (manapool.ContainsKey(poolName))
{
return (T)manapool[poolName];
}
// GameObject obj = new GameObject(poolName);
//obj.transform.SetParent(gamepool.transform);
T pool = new T();
manapool.Add(poolName, pool);
return pool;
}
public GameObject GetGameObject(string poolName, Vector3 position ) //用来获取对象池中对象,并判断是否对象池存在,不存在就新建。
{
if (manapool.ContainsKey(poolName))
{
return manapool[poolName].Getprfabe(position,poolName);
}
else
{
return Poolmanagement.instance.CreatGameObjectPool<Pool>(poolName).Getprfabe(position, poolName);
}
}
public void RemoveGameObject(string poolName, GameObject go) //用来移除对象,同样进行判断
{
if (manapool.ContainsKey(poolName))
{
manapool[poolName].Delprefab(go);
print("in remove");
}
else
{
Poolmanagement.instance.CreatGameObjectPool<Pool>(poolName);
manapool[poolName].Delprefab(go);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pool : MonoBehaviour {
private string poolname;
private int maxcountofprefab;//对象池里面最大数量
private GameObject prefab;//对象池里面实例化对象
public Queue<GameObject> prefabqueue;//pool队列
public Pool()
{
prefabqueue = new Queue<GameObject>();
}
//public void Init(Vector3 vector3)
//{
// GameObject.Instantiate(gameObject, vector3, Quaternion.identity);
//}
public GameObject Getprfabe(Vector3 vector3,string name) //获取对象池中prefab
{
if (prefabqueue.Count > 0)
{
prefab = prefabqueue.Dequeue(); //对象存在就出队列
prefab.transform.position = vector3;
prefab.SetActive(true);
return prefab;
}
else //不存在就按照名字加载资源,
{
GameObject gameObject = Resources.Load(name) as GameObject;
prefab =GameObject.Instantiate(gameObject);
prefab.transform.position = vector3;
return prefab;
}
print(name + " " + prefabqueue.Count);
}
public void Delprefab(GameObject prefab) //删除物体,进入对象池
{
if (prefabqueue.Contains(prefab)) //看对象池中是否有这个prefab,有的话就隐藏
{
// Destroy(prefab.GetComponent<MoveForward>());
prefab.SetActive(false);
}
else
{
//Destroy(prefab.GetComponent<MoveForward>());
prefab.SetActive(false); //如果没有,那就状态设置false后,进入队列
prefabqueue.Enqueue(prefab);
}
}
}
使用:
GameObject bullet = Poolmanagement.instance.GetGameObject("bullet", firePos.position);
Poolmanagement.instance.RemoveGameObject("bullet", bullet);
然后再设置相关Bullet的属性。