greyhh

记录学习中的点点滴滴
随笔 - 37, 文章 - 0, 评论 - 2, 阅读 - 76024

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

Unity中对象池的使用

Posted on   greyhh  阅读(7929)  评论(0编辑  收藏  举报

unity中用到大量重复的物体,例如发射的子弹,可以引入对象池来管理,优化内存。

对象池使用的基本思路是:

将用过的对象保存起来,等下一次需要这种对象的时候,再拿出来重复使用。恰当地使用对象池,可以在一定程度上减少频繁创建对象所造成的开销。

并非所有对象都适合拿来池化――因为维护对象池也要造成一定开销。对生成时开销不大的对象进行池化,反而可能会出现“维护对象池的开销”大于“生成新对象的开销”,从而使性能降低的情况。

GameObjectPool.cs如下

复制代码
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class GameObjectPool : MonoBehaviour {
    //单例模式
    private static GameObjectPool instance;

    public static GameObjectPool Instance
    {
        get { return GameObjectPool.instance; }
        set { GameObjectPool.instance = value; }
    }

    private static Dictionary<string, ArrayList> pool = new Dictionary<string, ArrayList>{ };
    // Use this for initialization
    void Start ()
    {
        Instance = this;
    }
    public static Object Get(string prefabName, Vector3 position, Quaternion rotation)
    {
        string key = prefabName + "(Clone)";
        Object o;
       //池中存在,则从池中取出
        if (pool.ContainsKey(key) && pool[key].Count>0)
        {
            ArrayList list=pool[key];
            o=list[0] as Object;
            list.Remove(o);
            //重新初始化相关状态
            (o as GameObject).SetActive(true);
            (o as GameObject).transform.position = position;
            (o as GameObject).transform.rotation = rotation;
        }
        //池中没有则实例化gameobejct
        else
        {
            o = Instantiate(Resources.Load(prefabName),position,rotation);
        }
          return o;
    }
    

public static Object Return(GameObject o) { string key = o.name; if (pool.ContainsKey(key)) { ArrayList list=pool[key]; list.Add(o); } else { pool[key] = new ArrayList(){ o}; } o.SetActive(false); return o; } }
复制代码

 

编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示