简单的对象池分三步走:
- 建立对象池
- 拿到对象
- 回收对象
Test为对象池,Obj为自动回收的物体
Test.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour {
//要复制的对象
public GameObject mCube;
//静态
public static Test instance;
//存储复制体,利用栈先进后出的机制
private Stack<GameObject> mStack = new Stack<GameObject>();
//初始化
private void Init(int count)
{
print("Init");
for (int i = 0; i < count; i++)
{
GameObject obj = Instantiate(mCube);
obj.gameObject.SetActive(false);
mStack.Push(obj);
}
print("GameObject"+mStack.Count);
}
//拿物体
public GameObject GetObj(Vector3 pos ,Quaternion rot)
{
print("get");
if(mStack.Count < 2)
{
Init(10);
}
GameObject g = mStack.Pop();
g.gameObject.SetActive(true);
g.transform.position = pos;
g.transform.rotation = rot;
return g;
}
//回收物体
public void Recycle(GameObject obj)
{
obj.gameObject.SetActive(false);
mStack.Push(obj);
}
void Start() {
instance = this;
Init(15);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
print("Space");
Test.instance.GetObj(this.transform.position, Quaternion.identity);
}
}
}
Obj.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Obj : MonoBehaviour {
private float mTime = 3f;
void Update () {
this.transform.position += Vector3.forward;
if (mTime > 0)
{
mTime -= Time.deltaTime;
if (mTime < 0)
{
Test.instance.Recycle(this.gameObject);
mTime = 3f;
}
}
}
}