對象池數組
using System.Collections;
using System.Collections.Generic;
using UnityEngine;函數
public class ObjectPool
{
private static ObjectPool instance;
/// <summary>
/// 對象池,字典中與key值對應的是數組(arraylist)(例:key爲手槍子彈 對應arraylist[手槍子彈,手槍子彈,手槍子彈。。。。。。 ])。
/// </summary>
private Dictionary<string, List<GameObject>> Pool;
/// <summary>
/// 預設體
/// </summary>
private Dictionary<string, GameObject> Prefabs;
//結構函數
private ObjectPool()
{
Pool = new Dictionary<string, List<GameObject>>();
Prefabs = new Dictionary<string, GameObject>();
}
#region 單例
public static ObjectPool GetInstance()
{
if (instance == null)
{
instance = new ObjectPool();
}
return instance;
}
#endregion
/// <summary>
/// 從對象池中獲取對象
/// </summary>
/// <param name="objName"></param>
/// <returns></returns>
public GameObject GetObj(string objName)
{
GameObject result = null;
//判斷是否有該名字的對象池 //對象池中有對象
if (Pool.ContainsKey(objName) && Pool[objName].Count > 0)
{
//獲取這個對象池中的第一個對象
result = Pool[objName][0];
//激活對象
result.SetActive(true);
//從對象池中移除對象
Pool[objName].Remove(result);
//返回結果
return result;
}
//若是沒有該名字的對象池或者該名字對象池沒有對象
GameObject Prefab = null;
if (Prefabs.ContainsKey(objName)) //若是已經加載過預設體
{
Prefab = Prefabs[objName];
}
else //若是沒有加載過預設體
{
//加載預設體
Prefab = Resources.Load<GameObject>("Obj/" + objName);
//更新預設體的字典
Prefabs.Add(objName, Prefab);
}
//實例化物體
result = UnityEngine.Object.Instantiate(Prefab);
//更名 去除Clone
result.name = objName;
return result;
}
/// <summary>
/// 回收對象到對象池
/// </summary>
public void RecycleObj(GameObject Obj)
{
Obj.SetActive(false);
//若是有該對象的對象池,直接放在池子中
if (Pool.ContainsKey(Obj.name))
{
Pool[Obj.name].Add(Obj);
}
else//若是沒有該對象的對象池,建立一個該類型的池子,並將對象放入
{
Pool.Add(Obj.name, new List<GameObject>() { Obj });
}
}
}
掛在子彈物體上(回收)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;this
public class Bullet : MonoBehaviour
{
public void OnEnable()
{
StartCoroutine(AutoRecycle());
}
//3秒後自動回收到對象池
IEnumerator AutoRecycle()
{
yield return new WaitForSeconds(3f);
ObjectPool.GetInstance().RecycleObj(this.gameObject);
}
}
用來使用對象池(調用)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;spa
public class test : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
ObjectPool.GetInstance().GetObj("Bullet");
}
}
}對象