对象池
一种通用型的技术,在其他语言中也会用到
1. 池
线程池、网络连接池,池是一个思想,将不用的东西暂时用池存起来,等到再次使用的时候再调出来用,节省CPU的调度
2. 对象
C#的任何一个类都可以实例化一个对象Object
Unity中的游戏对象GameObject
3. 思路
最开始的时候,池中没有对象,需要生成。用完之后放到池中。再次使用的时候再从池中获取
3.1 回收对象
把对象放到池中
3.2 获取对象
从池中获取对象
3.3 代码实现
using System.Collections.Generic;
using UnityEngine;
public class ObjectPool
{
#region 单例
// 声明单例
private static ObjectPool Instance;
/// <summary>
/// 获取单例
/// </summary>
/// <returns>The instance.</returns>
/// <param name="resPath">Res path.</param>
public static ObjectPool GetInstance(string resPath = "")
{
if (Instance == null)
{
if (resPath != "")
Instance = new ObjectPool(resPath);
else
Instance = new ObjectPool();
}
Instance.UpdateResourcePath(resPath);
return Instance;
}
// 构造函数
private ObjectPool()
{
prefabs = new Dictionary<string, GameObject>();
pools = new Dictionary<string, List<GameObject>>();
}
private ObjectPool(string resPath)
{
prefabs = new Dictionary<string, GameObject>();
pools = new Dictionary<string, List<GameObject>>();
resourcePath = resPath;
}
#endregion
#region 对象预设体资源管理
// 资源加载路径
private string resourcePath;
// 用字典存储所有的预设体
private Dictionary<string, GameObject> prefabs;
// 更新预设体加载路径
private void UpdateResourcePath(string resPath)
{
resourcePath = resPath;
}
// 获取预设体
private GameObject GetPrefab(string prefabName)
{
// 如果包含预设体,直接返回
if (prefabs.ContainsKey(prefabName))
return prefabs[prefabName];
// 如果不包含预设体,添加新的预设体,并返回
return LoadPrefab(prefabName);
}
// 加载预设体
private GameObject LoadPrefab(string prefabName)
{
// 拼接路径
string path = "";
if (resourcePath != "")
{
path += resourcePath;
}
// 加载预设体
GameObject obj = Resources.Load<GameObject>(path + prefabName);
// 存入字典
if (obj != null)
prefabs.Add(prefabName, obj);
// 返回
return obj;
}
#endregion
#region 对象池
// 对象池
private Dictionary<string, List<GameObject>> pools;
/// <summary>
/// 回收对象
/// </summary>
/// <param name="obj">Object.</param>
public void RecycleObject(GameObject obj)
{
// 非激活
obj.SetActive(false);
// 获取对象名称
string objName = obj.name.Replace("(Clone)", "");
// 判断有无该类对象池
// 如果没有,实例化一个子池
if (!pools.ContainsKey(objName))
pools.Add(objName, new List<GameObject>());
// 存入
pools[objName].Add(obj);
}
/// <summary>
/// 获取对象
/// </summary>
/// <returns>The object.</returns>
/// <param name="objName">Object name.</param>
/// <param name="poolEvent">Pool event.</param>
public GameObject SpawnObject(string objName, System.Action<GameObject> poolEvent = null)
{
// 声明一个输出结果
GameObject result = null;
// 如果有池,并且池中有对象
if (pools.ContainsKey(objName) && pools[objName].Count > 0)
{
result = pools[objName][0];
pools[objName].Remove(result);
}
// 如果没有池,或者池中没有对象,需要生成
else
{
// 拿到预设体
GameObject prefab = GetPrefab(objName);
if (prefab != null)
result = GameObject.Instantiate(prefab);
}
// 激活
result.SetActive(true);
// 执行事件
if (result && poolEvent != null)
poolEvent(result);
// 返回结果
return result;
}
#endregion
}
更多unity2018的功能介绍请到paws3d爪爪学院查找。链接https://www.paws3d.com/learn/,也可以加入unity学习讨论群935714213
近期更有资深开发人士直播分享unity开发经验,详情请进入官网或加入QQ群了解