利用C#队列Queue实现对象池。
方法 | 解释 |
---|---|
Enqueue() | 在队列的末端添加元素 |
Dequeue() | 在队列的头部读取一个元素并删除 |
Peek() | 在队列的头读取一个元素,但是不删除它 |
CopyTo() | 把队列中的元素复制到一个已有的数组中 |
ToArray() | 返回一个包含该队列元素的新数组 |
下面利用Enqueue入队和Dequeue出队来实现对象池。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pool : MonoBehaviour
{
public GameObject gameObjectPre;
public int gameObjectCount = 20;
public Queue<GameObject> avaiGameObjects = new Queue<GameObject>();//创建队列
private void Awake()
{
//初始化对象池
FillPool();
}
//填充对象池
public void FillPool()
{
int _i;
for(_i = 0;_i < gameObjectCount ;_i++)
{
var new_game_object = Instantiate(gameObjectPre);
new_game_object.transform.SetParent(transform);
BackToPool(new_game_object);
}
}
//入池
public void BackToPool(GameObject _gameobject)
{
//取消激活以返回对象池
_gameobject.SetActive(false);
avaiGameObjects.Enqueue(_gameobject);//入队
}
//出池
public GameObject UseObjectsInPool()
{
if(avaiGameObjects.Count == 0)//若池子里对象的数量不够,填充之。
{
FillPool();
}
var object_in_use = avaiGameObjects.Dequeue();//出队
object_in_use.SetActive(true);
return object_in_use;
}
}
复用池中对象,以减少分配内存、释放内存、创建堆中对象和销毁堆中对象的开销。
原文:https://www.cnblogs.com/OtusScops/p/14768789.html