之前做小遊戲整的,方便使用,存一下
代碼:
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的屬性。