Unity AssetBundle 之 (入门)简单的AssetBundle资源加载使用的案例

 

 

Unity AssetBundle 之 (入门)简单的AssetBundle资源加载使用的案例

 

目录

Unity AssetBundle 之 (入门)简单的AssetBundle资源加载使用的案例

一、简单介绍

二、实现原理

三、注意实现

四、效果预览

五、实现步骤

六、关键代码


 

一、简单介绍

Unity中的一些基础知识点。

本节介绍,Asset Bundle 在 Unity中的使用,入门第二篇,如何加载 AssetBundle标记打包的资源的案例,有不对的地方欢迎指正。

 

二、实现原理

1、www.assetBundle 加载 AB 资源包

2、ab.LoadAsset(assetName) 加载具体的资源

 

三、注意实现

1、Asset Bundle 加载的方法很多,这里只是其中的一种方法

2、加载具体的AssetBundle包的资源中具体资源的时候,可以不用加后缀,也可加载到指定资源(注意同一个AB包没有重名资源)

 

四、效果预览

 

五、实现步骤

1、打开Unity,新建一个空工程

 

2、把资源打包成 AB 包

可以参照 Unity AssetBundle 之 (入门)简单的资源打包成AB包的方法

 

3、在场景中添加一个 Cube ,待会把AB 包中的贴图资源付给他

 

4、编写代码,加载刚才打包的AB资源,把资源包中的图片添加给Cube

 

5、把脚本挂载到场景中,对应赋值 Cube

 

6、运行场景,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 + "/texturetest";
        assetName = "Floor.jpg";

        StartCoroutine(LoadNonObjectFromAB(url,go,assetName));
    }

    /// <summary>
    /// 协程加载 AssetBundle 资源
    /// </summary>
    /// <param name="ABURL"></param>
    /// <param name="goShowObj"></param>
    /// <param name="assetName"></param>
    /// <returns></returns>
    IEnumerator LoadNonObjectFromAB(string ABURL, GameObject goShowObj, string assetName) {
        // 参数检查
        if (string.IsNullOrEmpty(ABURL) || goShowObj ==null)
        {
            Debug.LogError(GetType()+ "/LoadNonObjectFromAB()/输入参数不合法,Please Check!");
        }

        using (WWW www = new WWW(ABURL)) {
            yield return www;
            AssetBundle ab = www.assetBundle;
            if (ab != null)
            {
                if (assetName == "")
                {
                    goShowObj.GetComponent<Renderer>().material.mainTexture = (Texture)ab.mainAsset;
                }
                else {
                    goShowObj.GetComponent<Renderer>().material.mainTexture = (Texture)ab.LoadAsset(assetName);

                }
            }
            else {
                Debug.LogError(GetType() + "/LoadNonObjectFromAB()/WWW 下载错误,Please Check! ABURL " +ABURL+" 错误信息:"+www.error);

            }
        }
        
    }


}

 

猜你喜欢

转载自blog.csdn.net/u014361280/article/details/107849222