当前位置:网站首页>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(); } }
边栏推荐
猜你喜欢

LeetCode 781. 森林中的兔子 哈希表/数学问题 medium

仅做两项修改,苹果就让StyleGANv2获得了3D生成能力

Understand the evolution of redis architecture in one article

Kubernetes CNI 分类/运行机制

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

If we were the developer responsible for repairing the collapse of station B that night

Graphical SQL is too vivid

视觉系统设计实例(halcon-winform)-10.PLC通讯

LeetCode 240. 搜索二维矩阵 II medium

如何做好企业系统漏洞评估
随机推荐
DIY制作示波器的超详细教程:(一)我不是为了做一个示波器
网络设备硬核技术内幕 路由器篇 17 DPDK及其前传(二)
LeetCode 783. 二叉搜索树节点最小距离 树/easy
终于有人把面试必考的动态规划、链表、二叉树、字符串全部撸完了
【云享读书会第13期】视频文件的封装格式
NEFU118 n! How many zeros are there after [basic theorem of arithmetic]
Nokia's patent business was hit for the first time, and Chinese enterprises are not so easy to knead
Notice of Nanshan District Civil Affairs Bureau on carrying out the grade evaluation of social organizations in Nanshan District in 2022
Zhou Hongyi: if the digital security ability is backward, it will also be beaten
Is there a regular and safe account opening platform for gold speculation
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
Timestamp of AAC, h264, etc
ADB command (install APK package format: ADB install APK address package name on the computer)
网络设备硬核技术内幕 路由器篇 5 汤普金森漫游网络世界(上)
Web page table table, realizing rapid filtering
How to do well in enterprise system vulnerability assessment
同花顺开户在手机开户安全吗?
网络设备硬核技术内幕 路由器篇 18 DPDK及其前传(三)
对话框管理器第三章:创建控件
IJCAI 2022杰出论文公布,大陆作者中稿298篇拿下两项第一