簡(jiǎn)單的對(duì)象池分三步走:
- 建立對(duì)象池
- 拿到對(duì)象
- 回收對(duì)象
Test為對(duì)象池,Obj為自動(dòng)回收的物體
Test.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour {
//要復(fù)制的對(duì)象
public GameObject mCube;
//靜態(tài)
public static Test instance;
//存儲(chǔ)復(fù)制體,利用棧先進(jìn)后出的機(jī)制
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;
}
}
}
}