【Unity3D】游戲?qū)ο蟪?/h2>
對象池思路.png
  • 代碼實(shí)現(xiàn)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class ObjectPool
{
    #region 單例

    private static ObjectPool instance;

    public static ObjectPool GetInstance(string resPath="")
    {
        if (instance==null)
        {
            if (resPath != null)
            {
                instance = new ObjectPool(resPath);
            }
            else
            {
                instance = new ObjectPool();
            }
        }

        instance.UpdateResourcePath(resPath);    

        return instance;
    }

    /// <summary>
    /// 構(gòu)造方法
    /// </summary>
    public ObjectPool()
    {
        prefabs = new Dictionary<string, GameObject>();
        pools = new Dictionary<string, List<GameObject>>();
    }

    /// <summary>
    /// 構(gòu)造方法
    /// </summary>
    /// <param name="resPath"></param>
    public ObjectPool(string resPath)
    {
        resourcePath = resPath;
        prefabs = new Dictionary<string, GameObject>();
        pools = new Dictionary<string, List<GameObject>>();
    }

    #endregion


    #region 對象預(yù)設(shè)體資源管理

    //資源加載路徑
    private string resourcePath;
    //所有預(yù)設(shè)體
    private Dictionary<string, GameObject> prefabs;

    public GameObject GetPrefab(string prefabName)
    {
        if (prefabs.ContainsKey(prefabName))
        {
            //返回
            return prefabs[prefabName];
        }
        else
        {
            //添加新的預(yù)設(shè)體
            return LoadPrefab((prefabName));
        }
    }

    /// <summary>
    /// 加載預(yù)設(shè)體
    /// </summary>
    /// <param name="prefabName"></param>
    /// <returns></returns>
    public GameObject LoadPrefab(string prefabName)
    {
        string path = "";
        if (resourcePath!= "")
        {
            path += resourcePath;
        }
        GameObject obj = Resources.Load<GameObject>(path + prefabName);
        //異常處理
        if (obj != null)
        {
            //放到字典
            prefabs.Add(prefabName, obj);
        }
        //返回
        return obj;
    }

    /// <summary>
    /// 更新預(yù)設(shè)體加載路徑
    /// </summary>
    /// <param name="resPath"></param>
    public void UpdateResourcePath(string resPath)
    {
        resourcePath = resPath;
    }

    #endregion

    #region 對象池

    private Dictionary<string, List<GameObject>> pools;

    /// <summary>
    /// 回收對象
    /// </summary>
    /// <param name="obj"></param>
    public void RecycleObject(GameObject obj)
    {
        //非激活
        obj.SetActive(false);
        //獲取對象的名稱
        string objName = obj.name.Replace("(Clone)", "");
        //判斷有無該類對象池
        if(!pools.ContainsKey(objName))
        {
            //實(shí)例化子池
            pools.Add(objName, new List<GameObject>());
        }
        //添加到池子
        pools[objName].Add(obj);
    }

    public GameObject SpawnObject(string objName,Action<GameObject> poolEvent=null)
    {
        //輸出結(jié)果
        GameObject result = null;

        //池中有貨
        if (pools.ContainsKey(objName)&&pools[objName].Count>0)
        {
            //結(jié)果
            result = pools[objName][0];
            //移除
            pools[objName].Remove(result);
        }
        else
        {
            //拿到預(yù)設(shè)體
            GameObject prefab = GetPrefab(objName);
            if (prefab!=null)
            {
               result = GameObject.Instantiate(prefab);
            }
        }

        //激活
        result.SetActive(true);

        //執(zhí)行事件
        if (result && poolEvent != null)
        {
            poolEvent(result);
        }

        //返回結(jié)果
        return result;
    }

    #endregion
}

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

public class Bullet : MonoBehaviour
{
    void OnEnable()
    {
        StartCoroutine(AutoRecycle());
    }

    IEnumerator AutoRecycle()
    {
        yield return new WaitForSeconds(2f);

        //回收
        ObjectPool.GetInstance().RecycleObject(gameObject);
    }
}

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

public class PoolDemo : MonoBehaviour
{
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            ObjectPool.GetInstance("Prefabs/").SpawnObject("Cube", (o) =>  
            {
                o.transform.position = new Vector3
                (
                    Random.Range(-5,5f),
                    Random.Range(-5, 5f),
                    Random.Range(-5, 5f)
                );
            });
        }
    }
}
對象池效果圖.gif
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 上篇文章介紹了,只需通過實(shí)現(xiàn) IObjectFactory 接口和繼承 Pool 類,就可以很方便地實(shí)現(xiàn)一個(gè)Sim...
    涼鞋的筆記閱讀 803評論 0 5
  • 1、通過CocoaPods安裝項(xiàng)目名稱項(xiàng)目信息 AFNetworking網(wǎng)絡(luò)請求組件 FMDB本地?cái)?shù)據(jù)庫組件 SD...
    陽明AI閱讀 16,222評論 3 119
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,281評論 25 708
  • 折騰了一宿,咱倆都沒休息好。你掛著兩只大眼袋,起床,胡亂地洗把臉,根本沒敢再碰我,連早飯也不敢吃,就徑直往醫(yī)院跑。...
    陌上紅裙閱讀 3,512評論 121 136
  • 學(xué)識(shí)滿腹不能展, 富有淵博史界源。 處世無知多碰壁, 艱難困苦力登攀。 ――讀《活著之上》有感
    六月天氣閱讀 228評論 15 24

友情鏈接更多精彩內(nèi)容