Unity-缓存池

一、.基础缓存池实现

继承的Singleton脚本为

cs 复制代码
public class Singleton<T> where T : new()
{
    private static T _instance;
    public static T GetIstance()
    {
        if (_instance == null)
            _instance = new T();
        return _instance;
    }
}

1.PoolManager

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

/// <summary>
/// 缓存池模块 
/// 1.Dictionary List
/// 2.Gameobject 和Resource两个公共类的API
/// </summary>
public class PoolManager : Singleton<PoolManager>
{
    //缓存池容器
    public Dictionary<string,List<GameObject>> poolDic = new Dictionary<string, List<GameObject>>();

    /// <summary>
    /// 从缓存池中拿
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    public GameObject GetObj(string name)
    {
        GameObject obj = null;
        //1.衣柜中有抽屉,抽屉里有东西
        if (poolDic.ContainsKey(name)&&poolDic[name].Count>0)
        {
            obj = poolDic[name][0];
            poolDic[name].RemoveAt(0);
        }
        //2.无
        else
        {
            obj = GameObject.Instantiate(Resources.Load<GameObject>(name));
            //将对象名字修改为池名字
            obj.name = name;
        }
        //激活对象
        obj.SetActive(true);
        return obj;
    }

    /// <summary>
    /// 存入缓存池
    /// </summary>
    /// <param name="name"></param>
    /// <param name="obj"></param>
    public void SaveObj(string name,GameObject obj)
    {
        //失活对象
        obj.SetActive(false);
        //1.有抽屉
        if (poolDic.ContainsKey(name))
        {
            //东西放入抽屉
            poolDic[name].Add(obj);
        }
        //2.无抽屉
        else
        {
            //创建抽屉
            poolDic.Add(name, new List<GameObject>(){ obj});
        }
    }
    
}

2.Test

挂载到摄像机上

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

public class Test : MonoBehaviour
{
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            PoolManager.GetIstance().GetObj("Test/Cube");
        }
    }
}

3.DlaySave

挂载到预制体Cube上

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

public class DelaySave : MonoBehaviour
{
    //当对象激活时,进入生命周期函数
    void OnEnable()
    {
        Invoke("Save", 1);
    }


    void Save()
    {
        PoolManager.GetIstance().SaveObj(this.gameObject.name, this.gameObject);
    }
}

二、缓存池优化

在生成物体时设置为Pool的子物体

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


/// <summary>
/// 抽屉数据  池子中的一列容器
/// </summary>
public class PoolData
{
    //抽屉中 对象挂载的父节点
    public GameObject fatherObj;
    //对象的容器
    public List<GameObject> poolList;

    public PoolData(GameObject obj, GameObject poolObj)
    {
        //给我们的抽屉 创建一个父对象 并且把他作为我们pool(衣柜)对象的子物体
        fatherObj = new GameObject(obj.name);
        fatherObj.transform.parent = poolObj.transform;
        poolList = new List<GameObject>() { };
        PushObj(obj);
    }

    /// <summary>
    /// 往抽屉里面 压都东西
    /// </summary>
    /// <param name="obj"></param>
    public void PushObj(GameObject obj)
    {
        //失活 让其隐藏
        obj.SetActive(false);
        //存起来
        poolList.Add(obj);
        //设置父对象
        obj.transform.parent = fatherObj.transform;
    }

    /// <summary>
    /// 从抽屉里面 取东西
    /// </summary>
    /// <returns></returns>
    public GameObject GetObj()
    {
        GameObject obj = null;
        //取出第一个
        obj = poolList[0];
        poolList.RemoveAt(0);
        //激活 让其显示
        obj.SetActive(true);
        //断开了父子关系
        obj.transform.parent = null;

        return obj;
    }
}

/// <summary>
/// 缓存池模块
/// 1.Dictionary List
/// 2.GameObject 和 Resources 两个公共类中的 API 
/// </summary>
public class PoolMgr : Singleton<PoolMgr>
{
    //缓存池容器 (衣柜)
    public Dictionary<string, PoolData> poolDic = new Dictionary<string, PoolData>();

    private GameObject poolObj;

    /// <summary>
    /// 往外拿东西
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    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;
    }

    /// <summary>
    /// 换暂时不用的东西给我
    /// </summary>
    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));
        }
    }


    /// <summary>
    /// 清空缓存池的方法 
    /// 主要用在 场景切换时
    /// </summary>
    public void Clear()
    {
        poolDic.Clear();
        poolObj = null;
    }
}
相关推荐
xcLeigh18 小时前
Unity基础:创建你的第一个游戏物体——Cube、Sphere与基本3D物体
游戏·3d·unity·教程
ellis197019 小时前
C#异常相关关键字:Exceptions,throw,try,catch,finally
unity·c#
HH‘HH1 天前
Unity通过OPC UA工业协议连接工业设备实战指南
unity·游戏引擎
め.2 天前
定点数运算库
算法·unity
点量云实时渲染-小芹2 天前
UE/Unity/Webgl模型在信创服务器上实时渲染推流的可行性分析
unity·webgl·云渲染信创·国产实时渲染·ue信创云推流
郝学胜-神的一滴2 天前
[简化版 GAMES 104] 现代游戏引擎 02:拆解现代游戏引擎5+1层级架构,吃透引擎底层核心逻辑
c++·unity·架构·游戏引擎·图形渲染·unreal engine·系统设计
unityのkiven2 天前
Unity 中如何创建一片森林:享元模式能不能用?应该怎么用?
unity·游戏引擎·享元模式
LONGZETECH2 天前
新能源汽车充电设备装配与调试仿真教学软件 技术架构与核心实现解析
大数据·算法·3d·unity·架构·汽车
丁小未2 天前
Unity 几种常见合批手段的要求
游戏·unity·合批·srpbatcher·动态合批·静态合批