对于多个对象池的使用,我提供了以下方式:
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上即可。
。这样的话就可以了...