本文共 2436 字,大约阅读时间需要 8 分钟。
对象池
一种通用型的技术,在其他语言中也会用到Unity中的游戏对象GameObject
3.1 回收对象
把对象放到池中3.2 获取对象
从池中获取对象3.3 代码实现
using System.Collections.Generic;using UnityEngine;public class ObjectPool
{// 声明单例
private static ObjectPool Instance;///
/// 获取单例/// /// The instance./// Res path.public static ObjectPool GetInstance(string resPath = ""){ if (Instance == null){ if (resPath != "")Instance = new ObjectPool(resPath);elseInstance = new ObjectPool();}Instance.UpdateResourcePath(resPath);return Instance;}// 构造函数private ObjectPool(){ prefabs = new Dictionary();pools = new Dictionary>();}private ObjectPool(string resPath){ prefabs = new Dictionary();pools = new Dictionary>();resourcePath = resPath;}// 资源加载路径
private string resourcePath;// 用字典存储所有的预设体private Dictionary 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(path + prefabName);// 存入字典if (obj != null)prefabs.Add(prefabName, obj);// 返回return obj;}// 对象池
private Dictionary> pools;///
/// 回收对象/// /// Object.public void RecycleObject(GameObject obj){ // 非激活obj.SetActive(false);// 获取对象名称string objName = obj.name.Replace("(Clone)", "");// 判断有无该类对象池// 如果没有,实例化一个子池if (!pools.ContainsKey(objName))pools.Add(objName, new List());// 存入pools[objName].Add(obj);}///
/// 获取对象/// /// The object./// Object name./// Pool event.public GameObject SpawnObject(string objName, System.Action poolEvent = null){ // 声明一个输出结果GameObject result = null;// 如果有池,并且池中有对象if (pools.ContainsKey(objName) && pools[objName].Count > 0){ result = poolsobjName;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;}}
转载地址:http://dittx.baihongyu.com/