嗚嗚喔學習筆記: 四月 2017

搜尋此網誌

2017年4月9日 星期日

Unity ObjectPool 物件池

再生成物件時 常常要大量創建跟銷毀
這樣很浪費效能 (比如說子彈之類的)

比較合理的做法可以做一個物件池
來回收資源再利用 (資源回收?)~

程式碼:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
public class ObjectPool
{
public Transform _parent = null;
private Queue<GameObject> _pool = new Queue<GameObject>();
private GameObject _prefab = null;
public ObjectPool(GameObject prefab, Transform parent = null)
{
_parent = parent;
_prefab = prefab;
}
public GameObject Spwan()
{
GameObject result = null;
if (_pool.Count > 0)
result = _pool.Dequeue();
else
result = UnityEngine.Object.Instantiate(_prefab);
result.gameObject.SetActive(true);
if (_parent)
result.transform.SetParent(_parent);
return result;
}
public T Spwan<T>() where T : Component
{
return Spwan() as T;
}
public void Despwan(GameObject go)
{
_pool.Enqueue(go);
go.SetActive(false);
}
}
使用方式


_objectPool = new ObjectPool(_prefab, _parent);
var go = _objectPool.Spwan(); -> 拿出來用 , 如果沒有的話 幫妳複製一個新的
_objectPool.Despwan(go); -> 不要用的東西丟回去池子裡