用途
避免頻繁地創(chuàng)建和銷(xiāo)毀對(duì)象
原理
預(yù)先創(chuàng)建若干對(duì)象
- 在要使用時(shí)選一個(gè)未被使用的進(jìn)行使用
- 在用完要銷(xiāo)毀時(shí)將其標(biāo)記為未使用而非銷(xiāo)毀,以供下次使用
實(shí)現(xiàn)
首先實(shí)現(xiàn)一個(gè)容器亡鼠,容器中有對(duì)象赏殃,用一個(gè)標(biāo)識(shí)符來(lái)標(biāo)記當(dāng)前對(duì)象是否被使用
/// <summary>
/// 供對(duì)象池使用的容器(Container):容器內(nèi)對(duì)象的內(nèi)容、標(biāo)記容器內(nèi)對(duì)象為已被(未被)使用
/// </summary>
/// <typeparam name="T"></typeparam>
public class ObjectPoolContainer<T>
{
// 容器內(nèi)對(duì)象
public T Item { get; set; }
// 容器內(nèi)對(duì)象是否已被使用的標(biāo)記
public bool Used { get; private set; }
// 標(biāo)記為已被使用
public void Consume()
{
Used = true;
}
// 標(biāo)記為未被使用
public void Release()
{
Used = false;
}
}
實(shí)現(xiàn)一個(gè)對(duì)象池间涵,該對(duì)象池中的對(duì)象可以是任意對(duì)象(Object)
使用時(shí)需先自行創(chuàng)建對(duì)象池實(shí)例仁热,在初始化時(shí)設(shè)置對(duì)象類(lèi)型和池的初始容量
使用舉例
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>
/// 一般對(duì)象的池子
/// </summary>
/// <typeparam name="T"></typeparam>
public class ObjectPool<T>
{
// 池中所有對(duì)象
private List<ObjectPoolContainer<T>> list;
// 已被使用的對(duì)象(用于查詢(xún))
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)
{
// 該委托用于返回一個(gè)(新創(chuàng)建的)對(duì)象實(shí)例
this.factoryFunc = factoryFunc;
list = new List<ObjectPoolContainer<T>>(initialSize);
lookup = new Dictionary<T, ObjectPoolContainer<T>>(initialSize);
Warm(initialSize);
}
// 初始時(shí)即生成capacity個(gè)對(duì)象
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中找得到還未被使用的對(duì)象,則使用該對(duì)象作為返回值
for (int i = 0; i < list.Count; i++)
{
lastIndex++;
// 最可能沒(méi)使用的就是上次使用了的下一個(gè)勾哩。若上次使用的是最后1個(gè)抗蠢,則這次只要從第0個(gè)開(kāi)始查
if (lastIndex > list.Count - 1)
lastIndex = 0;
if (list[lastIndex].Used)
continue;
else
{
container = list[lastIndex];
break;
}
}
// list中所有對(duì)象都被使用了,新創(chuàng)建一個(gè)對(duì)象
if (container == null)
container = CreateContainer();
// 標(biāo)記為已使用
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))
{
// 標(biāo)記為未使用
var container = lookup[item];
container.Release();
lookup.Remove(item);
}
}
}
實(shí)現(xiàn)一個(gè)用于Unity中游戲?qū)ο螅℅ameObject)的對(duì)象池
使用時(shí)直接調(diào)用相關(guān)靜態(tài)方法
使用舉例
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的區(qū)別是:GameObject可直接出現(xiàn)在場(chǎng)景(Scene)中
/// </summary>
public class GameObjectPool : Singleton<GameObjectPool>
{
public bool shouldShowLog;
public Transform root;
// 預(yù)制體-對(duì)象池
private Dictionary<GameObject, ObjectPool<GameObject>> prefabLookup;
// 實(shí)例-對(duì)象池(隸屬于同一預(yù)制體的實(shí)例對(duì)應(yīng)的對(duì)象池是一樣的)
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("“游戲?qū)ο蟪亍? 預(yù)制體名稱(chēng):{0} {1}個(gè)在被使用思劳,共有{2}個(gè)", item.Key.name, item.Value.CountUsedItems, item.Value.Count));
}
}
#region 靜態(tài)接口(供外部直接調(diào)用)
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
}