using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
using Debug = UnityEngine.Debug;
using Object = UnityEngine.Object;
//Simple ring buffer style pool system. You don't need to return the object to the pool, it just get pushed back to the
//end of the queue again. So use it only for object with short lifespan (projectile, particle system that auto disable)
public class PoolSystem : MonoBehaviour
{
public static PoolSystem Instance { get; private set; }
public static void Create()//创建一个对象池系统游戏对象
{
GameObject obj = new GameObject("PoolSystem");
Instance = obj.AddComponent<PoolSystem>();
}
Dictionary<Object, Queue<Object>> m_Pools = new Dictionary<Object, Queue<Object>>();
public void InitPool(UnityEngine.Object prefab, int size)//初始化对象池
{
if(m_Pools.ContainsKey(prefab))//是否有这个预制体
return;
Queue<Object> queue = new Queue<Object>();//对象队列
for (int i = 0; i < size; ++i)//起始设置
{
var o = Instantiate(prefab);
SetActive(o, false);
queue.Enqueue(o);
}
m_Pools[prefab] = queue;//给预制体对应的队列复制
}
public T GetInstance<T>(Object prefab) where T:Object//获取预制体实例,T为泛型
{
Queue<Object> queue;
if (m_Pools.TryGetValue(prefab, out queue))//出队
{
Object obj;
if (queue.Count > 0)
{
obj = queue.Dequeue();
}
else
{
obj = Instantiate(prefab);
}
SetActive(obj, true);
queue.Enqueue(obj);
return obj as T;
}
UnityEngine.Debug.LogError("No pool was init with this prefab");
return null;
}
static void SetActive(Object obj, bool active)//控制物体是否显示
{
GameObject go = null;
if (obj is Component component)
{
go = component.gameObject;
}
else
{
go = obj as GameObject;
}
go.SetActive(active);
}
}
Unity教学项目Ceator Kit:FPS 源代码学习笔记(三)PoolSystem类(对象池)
最新推荐文章于 2023-12-23 16:31:45 发布