Unity 对象池

为了解决大量创建重复对象造成的内存损耗,我们采用对象池的方式来解决。

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
 
 
public class PoolManager : MonoBehaviour {
 

 
    //单例模式,
    public static PoolManager instance;     
    Dictionary<string, List<GameObject>> pool = new Dictionary<string, List<GameObject>>() { };//使用字典作为对象池

    void Awake() {
        instance = this;//单例模式
    }
    /// <summary>
    /// 在对象池中取出物体
    /// </summary>
    /// <param name="go"></param>
    /// <param name="position"></param>
    /// <returns></returns>
    public GameObject GetPoolGameObject(GameObject go,Vector3 position)
    {
        if (go != null)
        {
            string key = go.name + "(Clone)";

            GameObject getGameObject;
            if (pool.ContainsKey(key) && pool[key].Count > 0)//当对象池中存在要取出的物体,且数量大于0即可取出
            {

                getGameObject = pool[key][0];
                pool[key].RemoveAt(0);
            }
            else if (pool.ContainsKey(key) && pool[key].Count <= 0)//当对象池中存在要取出的物体,但是数量不够时,需要实例化物体
            {

                getGameObject = Instantiate(go, position, Quaternion.identity) as GameObject;
            }
            else  //当对象池中不存在物体时,需要实例化物体并将物体添加到对象池中
            {

                getGameObject = Instantiate(go, position, Quaternion.identity) as GameObject;
                pool.Add(key, new List<GameObject>() { });
            }
            getGameObject.SetActive(true);
            getGameObject.transform.position = position;
            return getGameObject;
        }
        else {
            return null;
        }     
    }
 
    /// <summary>
    /// 回收物体到对象池中
    /// </summary>
    /// <param name="go"></param>
    public void IntoPoolByGameObject(GameObject go)
    {
       
        string key = go.name + "(Clone)";
        if (!pool.ContainsKey(key))
        {
            pool.Add(key, new List<GameObject>() { });
        }     
        pool[key].Add(go);
        go.SetActive(false);
    }    
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值