简单的AssetBundle打包、加载

设置资源文件的AssetBundle属性


简单的AssetBundle打包、加载_第1张图片
1.png
简单的AssetBundle打包、加载_第2张图片
2.png

创建打包脚本、打包

BuildAssetBundle.cs(使工具栏中出现BuildAssetBundle)


using System.IO;
using UnityEditor;
using UnityEngine;

public static class BuildAssetBundle
{
    [MenuItem("BuildAssetBundle/Bulid")]
    public static void Build()
    {
        CreateDirectory();
        BuildAssetBundles();

        //==========================================================

        /// 
        /// 创建StreamingAssets文件夹。若已存在则跳过
        /// 
        void CreateDirectory()
        {
            if (!Directory.Exists(Application.streamingAssetsPath))
                Directory.CreateDirectory(Application.streamingAssetsPath);

        }
        /// 
        /// 打包文件至StreamingAssets文件夹
        /// 
        void BuildAssetBundles()
        {
            BuildPipeline.BuildAssetBundles(
                Application.streamingAssetsPath,
                BuildAssetBundleOptions.None,
                BuildTarget.StandaloneWindows);
        }

    }

}
简单的AssetBundle打包、加载_第3张图片
3.png

编写测试脚本、测试

Test.cs(提供了两种加载方式)


using System.Collections;
using UnityEngine;
using UnityEngine.Networking;

namespace XiaoJie
{
    public class Test : MonoBehaviour
    {
        public GameObject m_Target;

        private string m_AbPath = Application.streamingAssetsPath + "/texture.v1";


        public void Test01()
        {
            ChangeTargetTexture(AssetBundle.LoadFromFile(m_AbPath),"Texture1");
        }
        public IEnumerator Test02()
        {
            UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(m_AbPath);
            yield return request.SendWebRequest();

            ChangeTargetTexture(
                DownloadHandlerAssetBundle.GetContent(request), "Texture2");
        }
        private void ChangeTargetTexture(AssetBundle ab , string textureName)
        {
            m_Target.GetComponent().material.mainTexture = 
                ab.LoadAsset(textureName);
            //相同的AB包被重复加载会返回null,这里要卸载掉
            ab.Unload(false);
        }
        private void OnGUI()
        {
            if(GUILayout.Button("Test01"))
            {
                Test01();
            }
            if (GUILayout.Button("Test02"))
            {
                StartCoroutine(Test02());
            }
        }
    }
}

简单的AssetBundle打包、加载_第4张图片
4.png
简单的AssetBundle打包、加载_第5张图片
5.png

你可能感兴趣的:(简单的AssetBundle打包、加载)