unity对象池技术

本文中代码来自brackeys视频教程中内容的整理;

原视频链接:

https://www.youtube.com/watch?v=tdSmKaJvCoA

代码如下:

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

public class PoolManager : SingletonBehaviour<PoolManager>
{
    // 具体的池子
    [System.Serializable]
    public class Pool
    {
        public string tag;
        public GameObject prefab;
        public int size;
    }

    public List<Pool> pools;
    // 池子管理
    public Dictionary<string, Queue<GameObject>> poolDictionary;

    // 开始时填满对象池,需要时可直接获取
    private void Start()
    {
        poolDictionary = new Dictionary<string, Queue<GameObject>>();

        foreach (Pool pool in pools)
        {
            Queue<GameObject> objectQueue = new Queue<GameObject>();

            for (int i = 0; i < pool.size; i++)
            {
                GameObject obj = Instantiate(pool.prefab);
                obj.SetActive(false);
                objectQueue.Enqueue(obj);
            }

            poolDictionary.Add(pool.tag, objectQueue);
        }
    }
    // 从对象池中生成
    public GameObject SpawnFromPool(string tag, Vector3 position, Quaternion rotation)
    {
        if (!poolDictionary.ContainsKey(tag))
        {
            Debug.LogWarning("Pool with tag " + tag + " doesn't exist! ");
            return null;
        }

        GameObject objectToSpawn = poolDictionary[tag].Dequeue();
        objectToSpawn.SetActive(true);
        objectToSpawn.transform.position = position;
        objectToSpawn.transform.rotation = rotation;

        poolDictionary[tag].Enqueue(objectToSpawn);

        return objectToSpawn;
    }
}
还见过另外一个不错的对象池博客,链接如下:

https://blog.csdn.net/qq_36927190/article/details/79475399


阅读更多
文章标签: unity 对象池
个人分类: unity 对象池
上一篇unity:一行代码写完加载进度条
下一篇unity插件dotween的使用
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭