对象池的实现

对象池:

就是一定数量的已经创建好的对象的集合。当需要创建对象时,先在池子中获取,如果池子中没有符合条件的对象,再进行创建新对象,同样,当对象需要销毁时,没有真正的销毁,而是将其Active设置为False,并存入池子中。避免了大量对象的创建,提高游戏性能。

对象池代码实现

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

//对象池的管理代码
public class MyPoolManager : MonoBehaviour
{
    //存储对象池的字典
    private static Dictionary<string, MyObjectPool> poolObjectDic = new Dictionary<string, MyObjectPool>();

    //创建对象池
    public static void CreatObjectPool(string poolName,GameObject prefab)
    {
        if (!poolObjectDic.ContainsKey(poolName))
        {
            poolObjectDic[poolName] = new MyObjectPool(prefab);
        }
    }

    /// <summary>
    /// 取某个对象池中的对象
    /// </summary>
    /// <param name="poolName">对象池名</param>
    /// <returns></returns>
    public static GameObject GetPoolObject(string poolName)
    {
        if (poolObjectDic.ContainsKey(poolName))
        {
           return  poolObjectDic[poolName].GetPoolObject();
        }
        else
        {
            Debug.LogError("该对象池不存在");
            return null;
        }
       
    }

    /// <summary>
    /// 回收某个对象池里的对象
    /// </summary>
    /// <param name="poolName">对象池名</param>
    /// <param name="obj">回收对象</param>
    /// <param name="parent">父节点</param>
    public static void RecyclePoolObject(string poolName,GameObject obj,Transform parent=null)
    {
        if (poolObjectDic.ContainsKey(poolName))
        {
            poolObjectDic[poolName].RecyclePoolObject(obj, parent);
        }
        else
        {
            Debug.LogError("该对象池不存在");
        }
    }
}

/// <summary>
/// 对象池实现
/// </summary>
public class MyObjectPool
{
    private GameObject prefab;
    private Stack<GameObject> pool = new Stack<GameObject>();

    public MyObjectPool(GameObject obj)
    {
        prefab = obj;
    }

    /// <summary>
    /// 从当前对象池获取对象
    /// </summary>
    public GameObject GetPoolObject()
    {
        GameObject objects;
        if (pool.Count >0)
        {
            objects = pool.Pop();
        }
        else
        {
            objects = Object.Instantiate(prefab);
            objects.name = prefab.name;
        }
        objects.gameObject.SetActive(true);
        return objects;
    }

    /// <summary>
    /// 回收对象到当前对象池
    /// </summary>
    public void RecyclePoolObject(GameObject obj,Transform parent)
    {
        if (parent!=null)
        {
            obj.transform.SetParent(parent,false);
        }
        //位置、旋转重置
        obj.transform.position=Vector3.zero;
        obj.transform.rotation =Quaternion.identity;
        obj.gameObject.SetActive(false);
        pool.Push(obj);
    }
}


上一篇:(三)AR Foundation开发


下一篇:Unity3D 用对象创建对象