1. 程式人生 > >Unity對象池的實現

Unity對象池的實現

res 結果 加載 using 判斷 instance 對象 dict unit

對象池是一個單例類:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectPool  {
    private static ObjectPool instance;
    private ObjectPool()
    {
        pool = new Dictionary<string, List<GameObject>>();
        prefabs = new Dictionary<string
, GameObject>(); } public static ObjectPool GetInstance() { if (instance==null) { instance = new ObjectPool(); } return instance; } /// <summary> /// 對象池 /// </summary> private Dictionary<string,List<GameObject>> pool;
/// <summary> /// 預設體 /// </summary> private Dictionary<string, GameObject> prefabs; /// <summary> /// 從對象池中獲取對象 /// </summary> /// <param name="objName"></param> /// <returns></returns> public GameObject GetObj(string objName) {
//結果對象 GameObject result=null; //判斷是否有該名字的對象池 if (pool.ContainsKey(objName)) { //對象池裏有對象 if (pool[objName].Count>0) { //獲取結果 result = pool[objName][0]; //激活對象 result.SetActive(true); //從池中移除該對象 pool[objName].Remove(result); //返回結果 return result; } } //如果沒有該名字的對象池或者該名字對象池沒有對象 GameObject prefab = null; //如果已經加載過該預設體 if (prefabs.ContainsKey(objName)) { prefab = prefabs[objName]; } else //如果沒有加載過該預設體 { //加載預設體 prefab = Resources.Load<GameObject>("Prefabs/"+objName); //更新字典 prefabs.Add(objName, prefab); } //生成 result = UnityEngine.Object.Instantiate(prefab); //改名(去除 Clone) result.name = objName; //返回 return result; } /// <summary> /// 回收對象到對象池 /// </summary> /// <param name="objName"></param> public void RecycleObj(GameObject obj) { //設置為非激活 obj.SetActive(false); //判斷是否有該對象的對象池 if (pool.ContainsKey(obj.name)) { //放置到該對象池 pool[obj.name].Add(obj); } else { //創建該類型的池子,並將對象放入 pool.Add(obj.name, new List<GameObject>() { obj }); } } }

以後要生成對象就獲取單例通過GetObj()來獲取,對象回收就調用RecycleObj(),這樣就減少了生成和銷毀預制體的性能消耗

Unity對象池的實現