当前位置:网站首页>Unity最简洁的对象池实现
Unity最简洁的对象池实现
2022-07-27 14:15:00 【傻子是小傲娇】
当要使用的对象要被多次创建和销毁时,采用对象池将不用的对象存起来而不是Destory,要用时再取出。
将两个脚本挂在空物体上,将预制体拖入,点击鼠标左键创建,右键回收。
/* 拿出时直接pop并加入此时管理的list并设为可见 放入时需判断当前的list有无元素,有则从当前remove,push并设为不可见 */ public class PoolTest : MonoBehaviour { //管理不在对象池中的对象 private List<GameObject> list=new List<GameObject>(); void Update() { if (Input.GetMouseButtonDown(0)) { GameObject go = GetComponent<PoolManager>().PoolPop(); go.SetActive(true); list.Add(go); } if (Input.GetMouseButtonDown(1)) { if (list.Count == 0) return; GetComponent<PoolManager>().PoolPush(list[0]); list[0].SetActive(false); list.RemoveAt(0); } } } //对象池管理器 /*Push Pop Clear push:当前个数没达到上限则Add,否则Destory pop: 个数不为0则取出并remove,为0则新建对象 */ //对象池管理器 public class PoolManager : MonoBehaviour { //存储对象的集合 public List<GameObject> list=new List<GameObject>(); //要生成的物体 public GameObject target; //对象池最大容量 public int maxSize = 100; public void PoolPush(GameObject go) { if (list.Count < maxSize) { list.Add(go); } else { Destroy(go); } } public GameObject PoolPop() { if (list.Count != 0) { GameObject temp = list[0]; list.RemoveAt(0); return temp; ; } else { return Instantiate(target); } } public void PoolClear() { list.Clear(); } }
边栏推荐
- Data warehouse project is never a technical project
- TXT把换行 替换为空格或者取消换行
- 数据仓库项目从来不是技术项目
- 于不确定中见“安全感” 沃尔沃2022年中问道
- ad7606与stm32连接电路介绍
- NEFU118 n! How many zeros are there after [basic theorem of arithmetic]
- Skywalking distributed system application performance monitoring tool - medium
- Graphic SQL of giant image
- NEFU118 n!后面有多少个0【算术基本定理】
- Nokia's patent business was hit for the first time, and Chinese enterprises are not so easy to knead
猜你喜欢
随机推荐
Unityui aspect processing (induction and accumulation)
The mobile terminal uses the list component of vantui. When multiple tab items are switched back and forth, the list is loaded many times, resulting in the failure of normal display of data
LeetCode 456. 132模式 单调栈/medium
一文搞懂 Redis 架构演化之路
网络设备硬核技术内幕 路由器篇 17 DPDK及其前传(二)
LeetCode 81. 搜索旋转排序数组 II 二分/medium
MySQL 面试40连问,面试官你再问下去我可要翻脸了
如何帮助企业优化Office管理
南山区民政局关于开展2022年度南山区社会组织等级评估工作的通知
DXGI 方式采集流程
FPGA时序约束分享04_output delay 约束
多表查询_练习1&练习2&练习3
Stm32f103c8t6 drives ssd1306 0.96 "IIC OLED display under Arduino frame
LeetCode 191. Number of 1 Bits(位1的个数) 位运算/easy
事务_基本演示和事务_默认自动提交&手动提交
If we were the developer responsible for repairing the collapse of station B that night
Getting started with DirectX
【WORK】关于技术架构
Do you really understand CMS garbage collector?
网络设备硬核技术内幕 路由器篇 3 贾宝玉梦游太虚幻境 (中)








