游戏 对象池

2018-08-25  本文已影响46人  BugUnknown
对象池思路.png
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>
    /// 构造方法
    /// </summary>
    public ObjectPool()
    {
        prefabs = new Dictionary<string, GameObject>();
        pools = new Dictionary<string, List<GameObject>>();
    }

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

    #endregion


    #region 对象预设体资源管理

    //资源加载路径
    private string resourcePath;
    //所有预设体
    private Dictionary<string, GameObject> prefabs;

    public GameObject GetPrefab(string prefabName)
    {
        if (prefabs.ContainsKey(prefabName))
        {
            //返回
            return prefabs[prefabName];
        }
        else
        {
            //添加新的预设体
            return LoadPrefab((prefabName));
        }
    }

    /// <summary>
    /// 加载预设体
    /// </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>
    /// 更新预设体加载路径
    /// </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))
        {
            //实例化子池
            pools.Add(objName, new List<GameObject>());
        }
        //添加到池子
        pools[objName].Add(obj);
    }

    public GameObject SpawnObject(string objName,Action<GameObject> poolEvent=null)
    {
        //输出结果
        GameObject result = null;

        //池中有货
        if (pools.ContainsKey(objName)&&pools[objName].Count>0)
        {
            //结果
            result = pools[objName][0];
            //移除
            pools[objName].Remove(result);
        }
        else
        {
            //拿到预设体
            GameObject prefab = GetPrefab(objName);
            if (prefab!=null)
            {
               result = GameObject.Instantiate(prefab);
            }
        }

        //激活
        result.SetActive(true);

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

        //返回结果
        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
上一篇 下一篇

猜你喜欢

热点阅读