使用对象池的目的:增加频繁使用的游戏物体的 复用性 (游戏物体(敌人小兵)反复的创建与销毁 会消耗比较多的性能)
创建对象池的步骤:
1.创建一个存放对象的字典(对象池)
2.对对象池的操作方法
2.1创建对象 CreateObject()
2.2为对象池添加元素 Add()
2.3寻找可以使用的对象 FindUseObj()
2.4回收对象 CollectObject()
3.释放资源 Clear();
实现如下
1.实现一个单例,用于管理代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MonoSingleton<T>:MonoBehaviour where T:Component
{
private static T t;
public static T Intance{
get{
t = GameObject.FindObjectOfType(typeof(T)) as T;
if(t==null)
{
GameObject go = new GameObject();
t = go.AddComponent<T>();
go.name = t + "Object";
}
//在场景切换时不要销毁
DontDestroyOnLoad(t);
return t;
}
}
}
2.实现对象池
using System.Collections;
using System.Collections.Generic;
using UnityEngine;