Unity使用对象池来解决子弹的频繁生成和销毁
1. 对象池用来干什么?
降低频繁生成和销毁对象的性能消耗,实现对象的反复使用。一般用于生成和销毁比较频繁的对象,比如:子弹,开火特效,爆炸特效等。
2. 解决子弹频繁生成和销毁案例
2-1. 场景搭建
两面墙壁加地板,还有一炮台
2-2. 单例脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Singleton<T> where T : class
{
private static T instance;
public static T Instance
{
get
{
if(instance == null)
{
instance = (T)System.Activator.CreateInstance(typeof(T), true);
}
return instance;
}
}
}
2-3. 对象池脚本
对象池
池子的数据结构 字典<对象名,List<对象类型>>
a. 需要用到对象的时候(拿)
(1). 先去池子看看有没有我所需要的对象,没有这个对象就去实例化
(2). 有我所需要用到的对象,则拿这个对象出来使用
b. 将对象放入对象池中(放)
(1). 如果该对象不是在池子中被拿出去的,则根据传递过来的Key新建一个新的列表将其保存
(2). 如果该对象有在池子中,则根据传递过来的Key将其保存到原来的列表中
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pool : Singleton<Pool>
{
private Dictionary<string, List<GameObject>> dic;
private Pool()
{
dic = new Dictionary<string, List<GameObject>