unity简单内存池案例
- 组件准备
- 代码部分
1.组件准备
在unity中创建一个空白物体命名为cubepawner,并拖到主摄像机之前
然后再创建cubepawner和cubePool脚本挂载到该物体上
再创建一个正方体,同时再创建一个空脚本,命名为cube 挂上去,并将该正方体拖入下方文件浏览器中制成预制体。代码编写完后需要将该预制体拖入各个脚本里
2.代码部分
cubepawner脚本代码内容如下:
//持续从池子中拉取物体
public GameObject cubeobject; void Update() { //Instantiate(cubeobject,transform.position,transform.rotation); GameObject cp = cubePool._instance.Get(); cp.transform.position = transform.position; }
cubePool脚本代码内容如下:
//对象池
public GameObject cubePrefab; public static cubePool _instance; private Queue<GameObject> cubeQueue = new Queue<GameObject>(); private void Awake() { _instance = this; //池添加初始内容,初始有500个正方体在池子里 for (int i = 0; i < 500; i++) { GameObject newcubeobj = Instantiate(cubePrefab); newcubeobj.SetActive(false); cubeQueue.Enqueue(Instantiate(cubePrefab)); } } //入池 public void Return(GameObject go) { go.SetActive(false); cubeQueue.Enqueue(go); } public GameObject Get() { //出池 if (cubeQueue.Count > 0) { GameObject cubeobj = cubeQueue.Dequeue(); cubeobj.SetActive(true); return cubeobj; } GameObject newcubeobj = Instantiate(cubePrefab); return newcubeobj; }
cube脚本代码内容如下:
void OnEnable() { //Destroy(this.gameObject,4f); StartCoroutine(ReturnObjectPool()); } IEnumerator ReturnObjectPool() { yield return new WaitForSeconds(3); //返回对象池 cubePool._instance.Return(this.gameObject); } }
标签:cubeQueue,GameObject,void,Instantiate,案例,unity,内存,cubePool,public From: https://www.cnblogs.com/wandn/p/18455136