對於多個對象池的使用,我提供了以下方式:
1,首先寫個管理類,記錄對象的生成方式:
我取名叫:MoreObjectPoolManager
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoreObjectPoolManager {
private GameObject objPre;
private int listSize;
private bool isAutoGrow;
private GameObject parentPoint;
private List<GameObject> listObj;
public MoreObjectPoolManager(GameObject _parentPoint,GameObject _obj,int _listSize,bool _isAutoGrow)
{
parentPoint = _parentPoint;
objPre = _obj;
listSize = _listSize;
isAutoGrow = _isAutoGrow;
listObj = new List<GameObject>();
for (int i = 0; i < listSize; i++)
{
GameObject obj = GameObject.Instantiate(objPre);
obj.transform.parent = parentPoint.transform;
obj.SetActive(false);
listObj.Add(obj);
}
}
public GameObject GetGameObject()
{
for (int i = 0; i < listObj.Count; i++)
{
if (!listObj[i].activeSelf)
{
listObj[i].SetActive(true);
return listObj[i];
}
}
if (isAutoGrow)
{
GameObject obj = GameObject.Instantiate(objPre);
obj.SetActive(true);
obj.transform.parent = parentPoint.transform;
listObj.Add(obj);
return obj;
}
Debug.LogError("GetGameObject is null.");
return null;
}
}
這個類不用集成MonoBehaviour。
其次,寫個類用於控制它的多個對象池的管理,我命名爲:MoreObjectPool
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public struct ObjectPoolInfo
{
public GameObject objPre;
public int objPoolSize;
public bool isAutoGrow;
}
public class MoreObjectPool: MonoBehaviour {
public static MoreObjectPool instance;
public ObjectPoolInfo[] objectPoolInfos;
public Dictionary<string, MoreObjectPool> objectPools;
void Awake () {
instance = this;
objectPools = new Dictionary<string, MoreObjectPool>();
OnInit();
}
public void OnInit()
{
for (int i = 0; i < objectPoolInfos.Length; i++)
{
if (objectPools.ContainsKey(objectPoolInfos[i].objPre.name))
{
Debug.Log("對象已存在");
}
else
{
MoreObjectPoolManager morePool = new MoreObjectPoolManager (this.gameObject, objectPoolInfos[i].objPre, objectPoolInfos[i].objPoolSize, objectPoolInfos[i].isAutoGrow);
objectPools.Add(objectPoolInfos[i].objPre.name, morePool);
}
}
}
public GameObject GetGameObjectPool(string objName)
{
return objectPools[objName].GetGameObject();
}
}
把這個腳本綁定在場景中的一個對象身上。如圖:
圖中我綁定的腳本是錯誤的,但是內容是正確的。
最後應該在Camera上綁定一個點擊事件。我命名爲:GetMoreObjectPool
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GetMoreObjectPool : MonoBehaviour {
void Update () {
if (Input.GetMouseButtonDown(0))
{
MoreObjectPoolManager.instance.GetGameObjectPool("Cube");
}
if (Input.GetMouseButtonDown(1))
{
MoreObjectPoolManager.instance.GetGameObjectPool("Sphere");
}
}
}
綁定在Camera上即可。
。這樣的話就可以了...