Unity3d Addressable Assets System可寻址资源管理系统
Overview
Addressable Assets 由以下三个插件包组成:
- Addressable Assets package (primary package) 本体
- Resource Manager package (dependency) 依赖
- Scriptable Build Pipeline package (dependency) 依赖
从Unity自带的Package Manager内安装Addressable时 以上3个packages都会一同下载安装好
Concepts
此处将会对Addressable内有关的名词对象进行注解
Addressable安装完毕后,将在项目目录下创建一个名为AddressableAssetData的文件夹
- Address 简单快速定义一个资源在run-time时可被追踪查询的地址
- AddressableAssetData directory 用来存储可寻址资源的Meta数据文件,以及相关打包和标记执行策略
- Asset Group 可寻址资源的集合,此集合用在build-time执行期间
- Asset Group Schema 可以被标记为组的一组数据集合,被使用在build时
- AssetReference 资源的绝对路径,或者存储资源的GUID以作为一个可寻址方式使用加载时
- Asynchronous Loading 简单来说就是异步加载,并且兼容之前的加载方式以期减少开发者的使用AAS的成本
- Build Script 运行在Asset Group Processors内,用来本来打包资源和Resource Manager使用这个脚在address和资源location之间建立联系
- Label 提供一种额外的可寻址资源定义方式,用来在run-time时更简单的加载或管理这个资源,举例:
LoadAll("spaceHazards");
Getting started with Addressable Assets
安装Addressable Assets package
Addressable Assets package需要unity 2018.2以上版本,可以简单的通过Package Manager来安装
使资源可寻址化
这里有两种简单的方式使资源可寻址化
- 在资源的Inspector界面,勾选Address框并输入一个用来定义资源的名称
- 从工具栏内打开Addressable窗口,把需要标记的资源拖入Addressable窗口的Group内
加载或实例化资源
Addressable同样提供了两种方式来加载或实例化资源,注意Addressable仅提供了异步方式,所以使用时必须提供一个回调方法!
访问资源的2种方式
-
Addressables.LoadAsset<GameObject>("AssetAddress");
-
Addressables.Instantiate<GameObject>("AssetAddress");
简单例子:
GameObject myGameObject;
...
Addressables.LoadAsset<GameObject>("AssetAddress").Completed += onLoadDone;
}
private void private void onLoadDone(UnityEngine.ResourceManagement.IAsyncOperation<Sprite> obj)
{
// In a production environment, you should add exception handling to catch scenarios such as a null result;
myGameObject = obj.Result;
}
使用AssetReference类
AssetReference类提供了一种不需要预先知道资源寻址名就可以访问资源的机制。
- 选择一个资源
- 在Inspector面板,添加一个脚本
- 在脚本内添加AssetReference对象:
public AssetReference explosion;
-
添加成功后后会在Inspector面板内提供一个访问接口,可以通过这个访问接口来选择之前已经添加入Addressable Assets面板内的所有资源,用以预定义可寻址资源已被之后的操作
使用AssetReference类加载资源和实例化
按照上面说的方法预先声明和准备资源对象,使用AssetReference内嵌方法来进行资源加载或实例化
注意AssetReference类同样也仅提供异步加载方式,所以必须要提供一个回调方法
简单例子:
[SerializeField]
private AssetReference m_assetRef;
[SerializeField]
private string m_prefabName;
void Start()
{
m_assetRef.InstantiateAsync().Completed += OnCompleted;
Addressables.InstantiateAsync(m_prefabName).Completed += OnCompletedByStringName;
}
private void OnCompletedByStringName(AsyncOperationHandle<GameObject> obj)
{
Debug.Log("[AddressableName][InstantiateAsync][Success]");
}
private void OnCompleted(AsyncOperationHandle<GameObject> obj)
{
Debug.Log("[AddressableREF][InstantiateAsync][Success]");
}
外部资源下载
Addressable Assets System提供了Addressables.PreloadDependencies()方法来加载所传入资源的依赖性,显而易见这就是asset bundle。并且提供了IAsyncOperation
对象来检测资源的下载和加载。具体内容不在本文内阐述。