主要参考 http://catlikecoding.com/unity/tutorials/ 教程:
Pool类和Object类;
Pool.cs 负责管理一个ObjectList 行为: GetPool获取static Pool GetObject AddObject
Object.cs 给外部 GetObject 和AddObjectToPool
项目中设置pool,会进行计算使用次数,一定时间后,如果没有使用,则清除。
using UnityEngine;
using System.Collections.Generic;
public class ObjectPool : MonoBehaviour
{
private List<PooledObject> mObjectList = new List<PooledObject>();
public static ObjectPool GetPool(PooledObject fobj)
{
string tempPoolName = fobj.name + "Pool";
ObjectPool tempPool = null;
GameObject tempPoolGameobj = GameObject.Find(tempPoolName);
if (tempPoolGameobj == null)
{
tempPoolGameobj = new GameObject(tempPoolName);
}
tempPool = tempPoolGameobj.GetComponent<ObjectPool>();
if (tempPool == null)
{
tempPool = tempPoolGameobj.AddComponent<ObjectPool>();
}
return tempPool;
}
/// <summary>
/// 获取缓冲区内的数据
/// </summary>
/// <returns></returns>
public PooledObject GetPoolObj(PooledObject fobj)
{
int tempIndex = mObjectList.Count - 1;
PooledObject tempObj = null;
if (tempIndex >= 0)
{
tempObj = mObjectList[tempIndex];
tempObj.gameObject.SetActive(true);
mObjectList.RemoveAt(tempIndex);
}
else
{
tempObj = Instantiate<PooledObject>(fobj);
tempObj.transform.SetParent(transform, false);
tempObj.mPool = this;
}
return tempObj;
}
/// <summary>
/// 向缓冲区内添加数据
/// </summary>
public void AddObjToPool(PooledObject fpoolObj)
{
fpoolObj.gameObject.SetActive(false);
mObjectList.Add(fpoolObj);
}
}
using UnityEngine;
public class PooledObject : MonoBehaviour
{
[System.NonSerialized]
public ObjectPool mPool = null;
public int testInt = 1;
//获取池中object
public T GetObject<T>() where T : PooledObject
{
if (mPool == null)
{
mPool = ObjectPool.GetPool(this);
}
testInt = 2;
return (T)mPool.GetPoolObj(this);
}
//把此object加入池中
public void AddObjToPool()
{
Debug.LogError("testInt :" + testInt);
if (mPool == null)
{
Debug.LogError("is null!!!!");
}
if (mPool != null)
{
mPool.AddObjToPool(this);
}
}
}