Unity_对象池

介绍

在项目中合理的使用对象池,减少频繁的创建、销毁对象,能有效的节约性能的开销。主要思路是在需要创建对象时先检测对象池中是否有可用对象,如果有直接取出,没有时再进行新建;在对象不再需要时将对象隐藏放入对象池等待下次需要时取出。当某个对象彻底不用时,可以将对应的对象池销毁减少内存的占用。

关键字

1. 单例模式
2. 对象池

代码

  • 单例

using UnityEngine;

/// <summary>
/// 单例
/// </summary>
public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
    private static T _instance;
    public static T Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = FindObjectOfType<T>();
                if (_instance == null)
                {
                    _instance = new GameObject(typeof(T).ToString()).AddComponent<T>();
                }
            }
            return _instance;
        }
    }
}
  • 对象池

using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 对象池
/// </summary>
public class ObjectPool : MonoSingleton<ObjectPool>
{
    private Dictionary<string, List<GameObject>> _objectDict;
    private Dictionary<string, GameObject> _prefabDict;
    /// <summary>
    /// 对象池
    /// </summary>
    private Dictionary<string, List<GameObject>> ObjectDict
    {
        get
        {
            if (_objectDict == null) _objectDict = new Dictionary<string, List<GameObject>>();
            return _objectDict;
        }

        set
        {
            _objectDict = value;
        }
    }
    /// <summary>
    /// 预设体字典
    /// </summary>
    private Dictionary<string, GameObject> PrefabDict
    {
        get
        {
            if (_prefabDict == null) _prefabDict = new Dictionary<string, GameObject>();
            return _prefabDict;
        }

        set
        {
            _prefabDict = value;
        }
    }

    /// <summary>
    /// 记录预设体字典
    /// </summary>
    /// <param name="obj"></param>
    public void SetPrefab(GameObject obj)
    {
        if (PrefabDict.ContainsKey(obj.name)) return;
        PrefabDict.Add(obj.name, obj);
    }

    /// <summary>
    /// 从对象池中获取对象
    /// </summary>
    /// <param name="objName"></param>
    /// <returns></returns>
    public GameObject GetObject(string objName, Transform parent = null)
    {
        if (parent == null) parent = transform;
        GameObject result = null;
        if (ObjectDict.ContainsKey(objName))
        {
            if (ObjectDict[objName].Count > 0)
            {
                result = ObjectDict[objName][0];
                result.transform.SetParent(parent);
                ObjectDict[objName].RemoveAt(0);
                return result;
            }
        }
        GameObject prefab = null;
        if (PrefabDict.ContainsKey(objName))
        {
            prefab = PrefabDict[objName];
        }
        else
        {
            Debug.LogError("[ObjectPool]:   prefab is null");
            return null;
            //prefab = Resources.Load<GameObject>("Prefabs/" + objName);
            //_prefabDict.Add(objName, prefab);
        }
        result = Instantiate(prefab, parent);
        result.name = objName;
        return result;
    }

    /// <summary>
    /// 回收对象到对象池
    /// </summary>
    /// <param name="objName"></param>
    public void RecycleObj(GameObject obj, Transform parent = null)
    {
        if (parent == null) parent = transform;
        obj.SetActive(false);
        obj.transform.SetParent(parent);
        if (ObjectDict.ContainsKey(obj.name))
        {
            ObjectDict[obj.name].Add(obj);
        }
        else
        {
            ObjectDict.Add(obj.name, new List<GameObject>() { obj });
        }
    }

    /// <summary>
    /// 删除对象池
    /// </summary>
    /// <param name="poolName"></param>
    public void DestoryPool(string poolName)
    {
        if (!_objectDict.ContainsKey(poolName)) return;
        List<GameObject> objs = _objectDict[poolName];
        for (int i = 0; i < objs.Count;)
        {
            Destroy(objs[i]);
            objs.RemoveAt(i);
        }
        _objectDict.Remove(poolName);
    }
}
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Unity中,虽然没有内置的对象类,但是可以通过自定义脚本来实现对象的功能。下面是一个简单的示例代码,展示了如何创建一个基本的对象: ```csharp using System.Collections.Generic; using UnityEngine; public class ObjectPool : MonoBehaviour { public GameObject prefab; // 预制体 public int poolSize; // 对象大小 private List<GameObject> objectPool; void Start() { objectPool = new List<GameObject>(); for (int i = 0; i < poolSize; i++) { GameObject obj = Instantiate(prefab); obj.SetActive(false); objectPool.Add(obj); } } public GameObject GetObjectFromPool() { for (int i = 0; i < objectPool.Count; i++) { if (!objectPool[i].activeInHierarchy) { objectPool[i].SetActive(true); return objectPool[i]; } } // 如果对象中没有可用对象,则动态创建一个新对象 GameObject newObj = Instantiate(prefab); objectPool.Add(newObj); return newObj; } public void ReturnObjectToPool(GameObject obj) { obj.SetActive(false); } } ``` 在上述代码中,我们创建了一个名为ObjectPool的脚本。在Start方法中,我们初始化了对象,根据poolSize的值来创建一定数量的对象,并将它们存储在objectPool列表中。 GetObjectFromPool方法用于从对象中获取一个可用的对象。我们遍历objectPool列表,寻找第一个处于非激活状态的对象,并将其设置为激活状态,然后返回该对象。如果对象中没有可用对象,则动态创建一个新对象,并将其添加到objectPool列表中。 ReturnObjectToPool方法用于将使用完的对象返回到对象中。我们将传入的对象设置为非激活状态,以便下次复用。 通过这样的自定义脚本,你可以在Unity中实现对象的功能,以提高游戏的性能和效率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值