Unity中對象池的使用


unity中用到大量重復的物體,例如發射的子彈,可以引入對象池來管理,優化內存。

對象池使用的基本思路是:

將用過的對象保存起來,等下一次需要這種對象的時候,再拿出來重復使用。恰當地使用對象池,可以在一定程度上減少頻繁創建對象所造成的開銷。

並非所有對象都適合拿來池化――因為維護對象池也要造成一定開銷。對生成時開銷不大的對象進行池化,反而可能會出現“維護對象池的開銷”大於“生成新對象的開銷”,從而使性能降低的情況。

GameObjectPool.cs如下

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

public class GameObjectPool : MonoBehaviour {
    //單例模式
    private static GameObjectPool instance;

    public static GameObjectPool Instance
    {
        get { return GameObjectPool.instance; }
        set { GameObjectPool.instance = value; }
    }

    private static Dictionary<string, ArrayList> pool = new Dictionary<string, ArrayList>{ };
    // Use this for initialization
    void Start ()
    {
        Instance = this;
    }
    public static Object Get(string prefabName, Vector3 position, Quaternion rotation)
    {
        string key = prefabName + "(Clone)";
        Object o;
       //池中存在,則從池中取出
        if (pool.ContainsKey(key) && pool[key].Count>0)
        {
            ArrayList list=pool[key];
            o=list[0] as Object;
            list.Remove(o);
            //重新初始化相關狀態
            (o as GameObject).SetActive(true);
            (o as GameObject).transform.position = position;
            (o as GameObject).transform.rotation = rotation;
        }
        //池中沒有則實例化gameobejct
        else
        {
            o = Instantiate(Resources.Load(prefabName),position,rotation);
        }
          return o;
    }
    

public static Object Return(GameObject o) { string key = o.name; if (pool.ContainsKey(key)) { ArrayList list=pool[key]; list.Add(o); } else { pool[key] = new ArrayList(){ o}; } o.SetActive(false); return o; } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM