当前位置:网站首页>Unity对象池实现
Unity对象池实现
2022-08-10 05:37:00 【诺贝尔男神获得者】
Unity对象池实现
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/**
* 对象池
*/
public class ObjectPool
{
//单例模式
private static ObjectPool instance = null;
private ObjectPool() { }
public static ObjectPool Instance
{
get
{
if (instance == null){
instance = new ObjectPool();
}
return instance;
}
}
//数据部分
Dictionary<string, List<GameObject>> pool = new Dictionary<string, List<GameObject>>();
//API部分
/// <summary>
/// 往对象池中放入某一游戏物体
/// </summary>
/// <param name="obj">要放到对象池中对象</param>
public void Put(GameObject obj)
{
//不是第一次的情况
if (pool.ContainsKey(obj.name))
{
pool[obj.name].Add(obj);
}else{
//第一次存入该类游戏物体
//声明一个新的列表装该类游戏物体
List<GameObject> list = new List<GameObject>();
//创建键名和键值的对应关系
pool.Add(obj.name, list);
//把游戏物体放到列表中
list.Add(obj);
}
//将放入对象池的物体隐藏
obj.SetActive(false);
}
/// <summary>
/// 从对象池中获取某一名字的游戏物体
/// </summary>
/// <param name="key">要获取的游戏物体名</param>
/// <returns></returns>
public GameObject Get(string key)
{
//检测是否存在该名字的物体
if (pool.ContainsKey(key))
{
//列表中是否还有剩余元素
if (pool[key].Count <= 0)
{
return null;
}else {
//拿到具体游戏物体并返回
GameObject obj = pool[key][0];
//将游戏物体从对象池中删除
pool[key].Remove(obj);
obj.SetActive(true);
return obj;
}
}else{
return null;
}
}
/// <summary>
/// 清空对象池,在跳转场景时调用
/// </summary>
public void Clear()
{
//static修饰的对象在unity中跳转场景时不会被释放
pool.Clear();
}
}
边栏推荐
猜你喜欢
C#对MySQL数据库进行增删改查操作(该操作还有防止MySQL注入功能)
STM32F407ZG GPIO输入相关实验
三种素数筛总结——(朴素筛,埃氏筛,线性筛)
51单片机教室人数进出统计检测数码管显示装置红外传感器
Convolutional Neural Network (CNN) for Clothing Image Classification
二维卷积定理的验证(下,cv2.filter2D())
pytorch-09. Multi-classification problem
STM32F407ZG 看门狗 IWDG & WWDG
开源游戏服务器框架NoahGameFrame(NF)服务器端环境搭建(二)
LeetCode refers to the offer 21. Adjust the order of the array so that the odd numbers are in front of the even numbers (simple)
随机推荐
STM32单片机LORA无线远程火灾报警监控系统DS18B20MQ2火焰检测
酸回收工艺原理
51单片机BH1750智能补光灯台灯光强光照恒流源LED控制系统
Unity中暂停、继续播放、杀死、正放、倒放Dotween动画
STM32单片机手机APP蓝牙高亮RGB彩灯控制板任意颜色亮度调光
基于MNIST数据集的简单FC复现
在Unity中判断游戏物体是否在游戏屏幕范围之内
工业废酸回收工艺
屏幕后期处理之:Sobel算子实现边缘检测
51单片机AD590温度测量ADC0832运放2.73V减法电压变换
Notes for RNN
pytorch-06.逻辑斯蒂回归
电池级碳酸氢锂除杂质钙镁离子工艺原理
通过配置CubeMX的TIMER的PWM初始化实现硬件PWM呼吸灯闪烁
LeetCode refers to the offer 21. Adjust the order of the array so that the odd numbers are in front of the even numbers (simple)
LeetCode Interview Question 17.14 Minimum k Number (Moderate)
Notes for RNN and Decision Tree
手机端应用类型
Notes for Netual Network
LaTeX总结----在CSDN上写出数学公式