动态代码设置assetbundleName,将一个纹理(Texture)文件夹打包,加载assetbundle

Unity最新的打包方式,是在面板上设置assetBundleName,然后利用 BuildPipeline.BuildAssetBundles()方法打包,如果现在的需求是打包一个文件夹下面所有的Texture,不可能一个一个区设置assetBundleName,下面是我根据网上看的一些博客,实际操作了下的代码,给大家参考吧

[MenuItem("Tools/BuildFileAssetBundle")]
        public static void BuildFileAssetBundle()
        {
            //设置好资源的assetsbundleName
            string assetPath = "Assets/Resources/Texture";
            AssetImporter assetImporter = AssetImporter.GetAtPath(assetPath);
            string assetName = Path.GetFileName(assetPath);
            //Debug.Log(assetName);
            //设置assetBndleName
            assetImporter.assetBundleName = assetName;
            //设置输出位置的路径
            string outputPath = Path.Combine(AssetBundlesOutputPath, GetPlatformFolder(EditorUserBuildSettings.activeBuildTarget));
            if (!Directory.Exists(outputPath))
            {
                Directory.CreateDirectory(outputPath);
            }
            //根据BuildSetting里面所激活的平台进行打成相应的平台包
            BuildPipeline.BuildAssetBundles(outputPath, 0, EditorUserBuildSettings.activeBuildTarget);
            //刷新
            AssetDatabase.Refresh();

            Debug.Log("打包完成");
        }

这里是将一个文件夹得内容打成一个包
我这里的资源路径是:”Assets/Resources/Texture”;
这里写图片描述

若无问题则,在unity面板中点击 Tools/BuildFileAssetBundle,将生成
这里写图片描述

下面 在写代码来加载

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace FW.Test
{
    class TestLoadAssetsBundle:UIEventBase
    {
        public Texture[] textureList;
        private float m_progress;
        IEnumerator Start()
        {
            string path = string.Empty;
            if (Application.platform.Equals(RuntimePlatform.WindowsEditor))
               path = "file://" + Application.dataPath + "/StreamingAssets/";
            if (Application.platform.Equals(RuntimePlatform.Android))
                path = "jar:file://" + Application.dataPath + "!/assets/";
            if (Application.platform.Equals(RuntimePlatform.IPhonePlayer))
                path = Application.dataPath + "/Raw/";
            using (WWW www = new WWW(path + "Android/texture"))
            {
                m_progress = www.progress;
                yield return www;
                string names = www.assetBundle.name;
                textureList = www.assetBundle.LoadAllAssets<Texture>();
                www.assetBundle.Unload(false);
            }
            foreach (var item in textureList)
            {
                Debug.Log("资源的名称----:"+ item.name);
            }
        }

        void Update()
        {

        }
    }
}

加载的几步
1 判断当前运行的平台,确定加载资源的路径
2 利用WWW加载 ,(是否要www.Dispose()看你的项目而定)
3 获取加载的资源 (我这里是获取所有的纹理)

以上我都实际操作过 ,有问题告知我

发布了38 篇原创文章 · 获赞 14 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/sinat_23156865/article/details/56479551
今日推荐