- 知识点:Dictionary, List, GameObject
- 作用: 节约性能, 减少CPU和内存消耗

没有缓存池,用完就删掉
有了缓存池,用完就放到缓存池(衣柜)
代码发现缓存池有,就不会实例化,而是使用缓存池中的对象
使用完后,又会放回到缓存池
“衣柜”中有不同的”抽屉”,只装对应的对象
代码
using System.Collections;using System.Collections.Generic;using UnityEngine;/// <summary>/// 缓存池模块/// 前置知识点:/// 1. Dictionary List/// 2. GameObject 和 Resources 两个公共类中的API/// </summary>public class PoolMgr : BaseManager<PoolMgr> // 单例模式{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;// 有抽屉且抽屉里有东西if (poolDic.ContainsKey(name) && poolDic[name].Count > 0){obj = poolDic[name][0];poolDic[name].RemoveAt(0); // 取出的从List中移除掉}else{// 抽屉里没有,则实例化一个新的返回出去// 规定预设体的路径作为抽屉的名字obj = GameObject.Instantiate(Resources.Load<GameObject>(name));obj.name = name; // 让对象的名字和外面传进来的名字一样,即资源路径名,也是我们规定的抽屉名,方便存进池子时获取名字}// 放进池子的对象是失活的,取出的时候要激活obj.SetActive(true);return obj;}/// <summary>/// 还暂时不用的对象/// </summary>public void PushObj(string name, GameObject obj){// 放进池子就要失活obj.SetActive(false);// 里面有抽屉if (poolDic.ContainsKey(name)){poolDic[name].Add(obj);}// 里面没有抽屉else{poolDic.Add(name, new List<GameObject>() { obj });}}}
使用
using System.Collections;using System.Collections.Generic;using UnityEngine;public class TestObj : MonoBehaviour{// Update is called once per framevoid Update(){if(Input.GetMouseButtonDown(0)){PoolMgr.GetInstance().GetObj("Test/Cube");}if (Input.GetMouseButtonDown(1)){PoolMgr.GetInstance().GetObj("Test/Sphere");}}}
using System.Collections;using System.Collections.Generic;using UnityEngine;public class DelayPush : MonoBehaviour{// 当对象激活时会进入的生命周期函数private void OnEnable(){Invoke("Push", 1);}void Push(){PoolMgr.GetInstance().PushObj(this.gameObject.name, this.gameObject);}}
作用
减小了GC的次数,内存换性能.
