Unity AssetBundle 之 (入门)简单的AssetBundle资源加载 Prefab 预制体 使用的案例
目录
Unity AssetBundle 之 (入门)简单的AssetBundle资源加载 Prefab 预制体 使用的案例
一、简单介绍
Unity中的一些基础知识点。
本节介绍,Asset Bundle 在 Unity中的使用,入门第三篇,如何加载 AssetBundle标记打包的资源的案例,这里加载的是预制体 Prefab ,有不对的地方欢迎指正。
二、使用原理
1、标记 对应的 Prefab,然后打包 AssetBundle
2、www.assetBundle 加载 AB 资源包
3、ab.LoadAsset(assetName) 加载具体的资源
三、注意实现
1、Asset Bundle 加载的方法很多,这里只是其中的一种方法
2、加载具体的AssetBundle包的资源中具体资源的时候,可以不用加后缀,也可加载到指定资源(注意同一个AB包没有重名资源)
四、效果预览
五、实现步骤
1、打开Unity,新建一个空工程
2、在场景中添加一个Cube ,给他赋值材质,做成一个预制体
3、给预制体 Cube 打上 标签
4、把资源打包成 AB 包
可以参照 Unity AssetBundle 之 (入门)简单的资源打包成AB包的方法
5、编写代码,加载刚才打包的AB资源,把资源包中的Prefab
6、把脚本挂载到场景中,对应赋值 Cube 显示位置
7、运行场景,Cube就被生成到指定位置了
六、关键代码
1、TestLoadAssetBundle
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestLoadAssetBundle : MonoBehaviour
{
//测试对象
public GameObject go;
// 资源下载地址和资源名称
private string url;
private string assetName;
// Start is called before the first frame update
void Start()
{
// 资源包的地址
url = Application.streamingAssetsPath + "/testprefab";
assetName = "Cube";
StartCoroutine(LoadPrefabFromAB(url, assetName, go.transform));
}
/// <summary>
/// 加载 prefab
/// </summary>
/// <param name="ABURL"></param>
/// <param name="assetName"></param>
/// <param name="showPosition"></param>
/// <returns></returns>
IEnumerator LoadPrefabFromAB(string ABURL, string assetName, Transform showPosition = null)
{
// 参数检查
if (string.IsNullOrEmpty(ABURL))
{
Debug.LogError(GetType() + "/LoadPrefabFromAB()/输入参数不合法,Please Check!");
}
using (WWW www = new WWW(ABURL))
{
yield return www;
AssetBundle ab = www.assetBundle;
if (ab != null)
{
if (assetName == "")
{
if (showPosition != null)
{
// 生成克隆对象
GameObject goCloneObj = (GameObject)Instantiate(ab.mainAsset);
//设置位置
goCloneObj.transform.position = showPosition.transform.position;
}
else {
// 生成克隆对象
Instantiate(ab.mainAsset);
}
}
else
{
if (showPosition != null)
{
// 生成克隆对象
GameObject goCloneObj = (GameObject)Instantiate(ab.LoadAsset(assetName));
//设置位置
goCloneObj.transform.position = showPosition.transform.position;
}
else
{
// 生成克隆对象
Instantiate(ab.LoadAsset(assetName));
}
}
}
else
{
Debug.LogError(GetType() + "/LoadPrefabFromAB()/WWW 下载错误,Please Check! ABURL " + ABURL + " 错误信息:" + www.error);
}
}
}
}