用途
避免频繁地创建和销毁对象
原理
预先创建若干对象
- 在要使用时选一个未被使用的进行使用
- 在用完要销毁时将其标记为未使用而非销毁,以供下次使用
实现
首先实现一个容器,容器中有对象,用一个标识符来标记当前对象是否被使用
/// <summary>
/// 供对象池使用的容器(Container):容器内对象的内容、标记容器内对象为已被(未被)使用
/// </summary>
/// <typeparam name="T"></typeparam>
public class ObjectPoolContainer<T>
{
// 容器内对象
public T Item { get; set; }
// 容器内对象是否已被使用的标记
public bool Used { get; private set; }
// 标记为已被使用
public void Consume()
{
Used = true;
}
// 标记为未被使用
public void Release()
{
Used = false;
}
}
实现一个对象池,该对象池中的对象可以是任意对象(Object)
使用时需先自行创建对象池实例,在初始化时设置对象类型和池的初始容量
使用举例
private ObjectPool<MyObj> myObjPool = new ObjectPool<MyObj>(() => new MyObj(), 10);
var myObj = myObjPool.GetItem();
myObjPool.ReleaseItem(myObj);
ObjectPool.cs
using System;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 一般对象的池子
/// </summary>
/// <typeparam name="T"></typeparam>
public class ObjectPool<T>
{
// 池中所有对象
private List<ObjectPoolContainer<T>> list;
// 已被使用的对象(用于查询)
private Dictionary<T, ObjectPoolContainer<T>> lookup;
private Func<T> factoryFunc;
private int lastIndex;
public int Count { get { return list.Count; } }
public int CountUsedItems { get { return lookup.Count; } }
public ObjectPool(Func<T> factoryFunc, int initialSize)
{
// 该委托用于返回一个(新创建的)对象实例
this.factoryFunc = factoryFunc;
list = new List<ObjectPoolContainer<T>>(initialSize);
lookup = new Dictionary<T, ObjectPoolContainer<T>>(initialSize);
Warm(initialSize);
}
// 初始时即生成capacity个对象
private void Warm(int capacity)
{
for (int i = 0; i < capacity; i++)
{
CreateContainer();
}
}
private ObjectPoolContainer<T> CreateContainer()
{
var container = new ObjectPoolContainer<T>();
container.Item = factoryFunc();
list.Add(container);
return container;
}
public T GetItem()
{
ObjectPoolContainer<T> container = null;
// 若在list中找得到还未被使用的对象,则使用该对象作为返回值
for (int i = 0; i < list.Count; i++)
{
lastIndex++;
// 最可能没使用的就是上次使用了的下一个。若上次使用的是最后1个,则这次只要从第0个开始查
if (lastIndex > list.Count - 1)
lastIndex = 0;
if (list[lastIndex].Used)
continue;
else
{
container = list[lastIndex];
break;
}
}
// list中所有对象都被使用了,新创建一个对象
if (container == null)
container = CreateContainer();
// 标记为已使用
container.Consume();
lookup.Add(container.Item, container);
return container.Item;
}
public void ReleaseItem(object item)
{
ReleaseItem((T)item);
}
public void ReleaseItem(T item)
{
if (lookup.ContainsKey(item))
{
// 标记为未使用
var container = lookup[item];
container.Release();
lookup.Remove(item);
}
}
}
实现一个用于Unity中游戏对象(GameObject)的对象池
使用时直接调用相关静态方法
使用举例
GameObjectPool.WarmPool(prefab, 10);
var go = GameObjectPool.CreateObject(prefab, positon, rotation);
GameObjectPool.ReleaseObject(go);
GameObjectPool.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Unity中GameObject的池子
/// 与一般Object的区别是:GameObject可直接出现在场景(Scene)中
/// </summary>
public class GameObjectPool : Singleton<GameObjectPool>
{
public bool shouldShowLog;
public Transform root;
// 预制体-对象池
private Dictionary<GameObject, ObjectPool<GameObject>> prefabLookup;
// 实例-对象池(隶属于同一预制体的实例对应的对象池是一样的)
private Dictionary<GameObject, ObjectPool<GameObject>> instanceLookup;
private bool hasRefreshedLog = false;
private void Awake()
{
Init();
}
private void Update()
{
if (shouldShowLog && hasRefreshedLog)
{
ShowLog();
hasRefreshedLog = false;
}
}
private void Init()
{
prefabLookup = new Dictionary<GameObject, ObjectPool<GameObject>>();
instanceLookup = new Dictionary<GameObject, ObjectPool<GameObject>>();
}
public void WarmPoolNonStatic(GameObject prefab, int size, bool isActive)
{
var pool = new ObjectPool<GameObject>(() => { return InstantiatePrefab(prefab, isActive); }, size);
prefabLookup[prefab] = pool;
hasRefreshedLog = true;
}
public GameObject CreateObjectNonStatic(GameObject prefab)
{
return CreateObjectNonStatic(prefab, Vector3.zero, Quaternion.identity);
}
public GameObject CreateObjectNonStatic(GameObject prefab, Vector3 position, Quaternion rotation)
{
if (!prefabLookup.ContainsKey(prefab))
WarmPool(prefab, 1, true);
var pool = prefabLookup[prefab];
var go = pool.GetItem();
go.transform.position = position;
go.transform.rotation = rotation;
go.SetActive(true);
instanceLookup.Add(go, pool);
hasRefreshedLog = true;
return go;
}
public void ReleaseObjectNonStatic(GameObject go)
{
go.SetActive(false);
if (instanceLookup.ContainsKey(go))
{
instanceLookup[go].ReleaseItem(go);
instanceLookup.Remove(go);
hasRefreshedLog = true;
}
}
private GameObject InstantiatePrefab(GameObject prefab, bool isActive)
{
var go = Instantiate(prefab) as GameObject;
if (isActive)
go.SetActive(true);
else
go.SetActive(false);
if (root != null)
go.transform.parent = root;
return go;
}
public void ShowLog()
{
foreach (var item in prefabLookup)
{
Debug.Log(string.Format("“游戏对象池” 预制体名称:{0} {1}个在被使用,共有{2}个", item.Key.name, item.Value.CountUsedItems, item.Value.Count));
}
}
#region 静态接口(供外部直接调用)
public static void WarmPool(GameObject prefab, int size, bool isActive = false)
{
Instance.WarmPoolNonStatic(prefab, size, isActive);
}
public static GameObject CreateObject(GameObject prefab)
{
return Instance.CreateObjectNonStatic(prefab);
}
public static GameObject CreateObject(GameObject prefab, Vector3 position, Quaternion rotation)
{
return Instance.CreateObjectNonStatic(prefab, position, rotation);
}
public static void ReleaseObject(GameObject go)
{
Instance.ReleaseObjectNonStatic(go);
}
#endregion
}