【U3D/简单框架】2.缓存对象池

自我介绍

广东双非一本的大三小白,计科专业,想在制作毕设前夯实基础,毕设做出一款属于自己的游戏!

对象池

  • 当我们在unity场景中需要多次重复的对某一个GameObject进行创建和销毁时,减少GC给游戏带来的卡顿。
  • 当我们在unity中销毁物体上,并不会真的在内存中去释放空间,只是断开引用,最终的释放空间是在当内存满的时候进行GC
  • 当场景中不需要该GameObject时,不进行销毁,只是将其隐藏,放在对象池中管理,需要时从对象池中拿出来显示
  • 在unity,往往不止需要一种GameObject的对象池,这时我们需要用到字典(Dictionary)来存放和区分对象池)

缓存池模块

我们需要两个池子:

  • 小池子 PoolData.cs 为了解决层级问题,一个pool管理一种东西
  • 大池子 PoolManager.cs 相当于管理所有小池子

PoolData.cs

using System.Collections.Generic;
using UnityEngine;

public class PoolData
{
    public GameObject fatherObj;    // 对象挂载的父节点
    public List<GameObject> poolList;

    public PoolData(GameObject obj, GameObject poolObj)
    {
        fatherObj = new GameObject(obj.name);
        fatherObj.transform.parent = poolObj.transform;
        poolList = new List<GameObject>() { obj };
        PushObj(obj);
    }

    public void PushObj(GameObject obj)
    {
        obj.SetActive(false);
        poolList.Add(obj);
        obj.transform.parent = fatherObj.transform;
    }

    public GameObject GetObj()
    {
        GameObject obj = null;
        obj = poolList[0];
        poolList.RemoveAt(0);
        obj.SetActive(true);
        obj.transform.parent = null;

        return obj;
    }
}

核心 PoolManager.cs 封装

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

public class PoolManager : BaseSingleton<PoolManager>
{
    public Dictionary<string, PoolData> poolDic = new Dictionary<string, PoolData>();

    private GameObject poolObj;

    public GameObject GetObj(string name)
    {
        GameObject obj = null;
        if (poolDic.ContainsKey(name) && poolDic[name].poolList.Count > 0)
        {
            obj = poolDic[name].GetObj();
        }
        else
        {
            obj = GameObject.Instantiate(Resources.Load<GameObject>(name));
            obj.name = name;
        }
        return obj;
    }

    public void PushObj(string name, GameObject obj)
    {
        if (poolObj == null) poolObj = new GameObject("Pool");

        if (poolDic.ContainsKey(name))
        {
            poolDic[name].PushObj(obj);
        }
        else
        {
            poolDic.Add(name, new PoolData(obj, poolObj));
        }
    }

    // 清空缓存池的方法,主要用于场景切换
    public void Clear()
    {
        poolDic.Clear();
        poolObj = null;
    }
}

测试 Test.cs 随便挂载到一个物体上,主要用缓存池来生成对象

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        GameObject go = PoolManager.Instance().GetObj("Cube");
        StartCoroutine(Back(go));
    }

    if (Input.GetMouseButtonDown(1))
    {
        GameObject go = PoolManager.Instance().GetObj("Sphere");
        StartCoroutine(Back(go));
    }
}

IEnumerator Back(GameObject go)
{
    yield return new WaitForSeconds(1f);
    PoolManager.Instance().PushObj(go.name, go);
}

生成的对象是预制体,放在Resources里,上面测试脚本的协程是用于1秒后放回缓存池

效果

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章