您现在的位置是:首页 > 文章详情

Unity框架与资源打包

日期:2019-04-01点击:381

对象池
一种通用型的技术,在其他语言中也会用到


  1. 线程池、网络连接池,池是一个思想,将不用的东西暂时用池存起来,等到再次使用的时候再调出来用,节省CPU的调度
  1. 对象
    C#的任何一个类都可以实例化一个对象Object

Unity中的游戏对象GameObject

  1. 思路
    最开始的时候,池中没有对象,需要生成。用完之后放到池中。再次使用的时候再从池中获取

3.1 回收对象
把对象放到池中

3.2 获取对象
从池中获取对象

3.3 代码实现
using System.Collections.Generic;
using UnityEngine;

public class ObjectPool
{

region 单例

// 声明单例
private static ObjectPool Instance;

///
/// 获取单例
///
/// The instance.
/// Res path.
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();
pools = new Dictionary>();
}
private ObjectPool(string resPath)
{
prefabs = new Dictionary();
pools = new Dictionary>();
resourcePath = resPath;
}

endregion

region 对象预设体资源管理

// 资源加载路径
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;
}

endregion

region 对象池

// 对象池
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;
}

endregion

}

原文链接:https://yq.aliyun.com/articles/696471
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章