Unity5 AssetBundle 打包以及加载

时间:2021-06-28 00:34:16
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using System.IO; public class BuildAssetBundle : Editor { //需要打包的路径,根据项目具体需求自己定
private static string assetPath = "AllAssets"; //导出包路径
private static string AssetBundleOutPsth = "Assets/StreamingAssets"; //保存需要打包的资源路径
private static List<string> assetPathList = new List<string>(); //需要打包的资源后缀
private static Dictionary<string, string> asExtensionDic = new Dictionary<string, string> (); [MenuItem("Assets/BuildAssetBundle")]
private static void BuildAssetBundleSource()
{
assetPathList.Clear (); //根据不同平台拼接不同平台导出路径
string outPsth = Path.Combine (AssetBundleOutPsth, Plathform.GetPlatformFolder(EditorUserBuildSettings.activeBuildTarget)); GetDirs(Application.dataPath + "/" + assetPath); BuildAsset (outPsth);
} //添加需要打包资源的后缀
private static void SetASExtensionDic ()
{
asExtensionDic.Clear (); asExtensionDic.Add (".prefab", ".unity3d");
asExtensionDic.Add (".mat", ".unity3d");
asExtensionDic.Add (".png", ".unity3d");
} //遍历制定文件夹获取需要打包的资源路径
private static void GetDirs(string dirPath)
{
foreach (string path in Directory.GetFiles(dirPath))
{
// 通过资源后缀判断资源是否为需要打包的资源
if (asExtensionDic.ContainsKey(System.IO.Path.GetExtension(path)))
{
//将需要打包的资源路径添加到打包路劲中
assetPathList.Add(path);
}
} if (Directory.GetDirectories(dirPath).Length > ) //遍历所有文件夹
{
foreach (string path in Directory.GetDirectories(dirPath))
{
//使用递归方法遍历所有文件夹
GetDirs(path);
}
}
} //清除已经打包的资源 AssetBundleNames
private static void ClearAssetBundlesName()
{
int length = AssetDatabase.GetAllAssetBundleNames ().Length;
Debug.Log (length);
string[] oldAssetBundleNames = new string[length];
for (int i = ; i < length; i++)
{
oldAssetBundleNames[i] = AssetDatabase.GetAllAssetBundleNames()[i];
} for (int j = ; j < oldAssetBundleNames.Length; j++)
{
AssetDatabase.RemoveAssetBundleName(oldAssetBundleNames[j],true);
}
} //打AS包
private static void BuildAsset(string outPath)
{
//遍历获取到的打包资源路径
for (int i = ; i < assetPathList.Count; i ++)
{
string asPath = assetPathList[i]; //通过资源路径来获取需要打包的资源
AssetImporter assetImporter = AssetImporter.GetAtPath(asPath);
if (assetImporter == null)
{
continue;
} // 从此处(assetPath = "AllAssets")截取路径
string assetName = asPath.Substring(asPath.IndexOf(assetPath));
//替换后缀名
assetName = assetName.Replace(Path.GetExtension(assetName), ".unity3d");
//设置打包资源的名字包括后缀
assetImporter.assetBundleName = assetName;
} //如果不存在到处路径文件,创建一个
if (!Directory.Exists (outPath)) {
Directory.CreateDirectory(outPath);
} //打包
BuildPipeline.BuildAssetBundles (outPath, , EditorUserBuildSettings.activeBuildTarget); //刷新资源路径,避免生成的文件不显示
AssetDatabase.Refresh ();
}
} //根据切换的平台返回相应的导出路径
public class Plathform
{
public static string GetPlatformFolder(BuildTarget target)
{
switch (target)
{
case BuildTarget.Android: //Android平台导出到 Android文件夹中
return "Android";
case BuildTarget.iOS:
return "IOS";
case BuildTarget.WebPlayer:
return "WebPlayer";
case BuildTarget.StandaloneWindows:
case BuildTarget.StandaloneWindows64:
return "Windows";
case BuildTarget.StandaloneOSXIntel:
case BuildTarget.StandaloneOSXIntel64:
case BuildTarget.StandaloneOSXUniversal:
return "OSX";
default:
return null;
}
} }

操作如下,以项目为例

Unity5 AssetBundle 打包以及加载

Unity5 AssetBundle 打包以及加载

在 StreamingAssets文件夹下生成AB文件

Unity5 AssetBundle 打包以及加载

打比完毕,每个资源自动打包出两个文件

Unity5 AssetBundle 打包以及加载

下面是加载,封装了一下加载代码如下

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.IO; // 回调方法
public delegate void CallBack(UnityEngine.Object obj); // AS 文件只能加载一次,重复加载出错,两种方案,
// 一、加载后卸载,下次需要使用时重新加载,
// 二、加载后将AS保存起来,下载加载相同AS时直接取出来使用
public class LoadAssetBundle{
//单例
public static readonly LoadAssetBundle Instance = new LoadAssetBundle(); private string path = Application.streamingAssetsPath; //保存加载的AS
private Dictionary<string, AssetBundle> assetBundleRefDic = new Dictionary<string, AssetBundle>(); //PC本地资源需加上 "file://"
private string GetThePathWithPlathform
{
get
{
if (Application.isEditor)
{
return "file://" + path;
}
else
{
return path;
}
}
} // 加载后释放
// assetPath 加载资源路径
// assetName 资源名
// type 加载资源类型
// callBack 加载完成回调
// isUnload 加载后是否卸载
public IEnumerator Load(string assetPath, string assetName, Type type, CallBack callBack, bool isUnload)
{
string loadpath = GetThePathWithPlathform;
string url = Path.Combine(loadpath, assetPath); AssetBundle ab = GetASFromUrl (url); if (ab != null) {
GetObject (ab, assetName, type, callBack, isUnload); yield return null;
}
else
{
WWW www = WWW.LoadFromCacheOrDownload (url, ); yield return www; if (!string.IsNullOrEmpty (www.error)) {
Debug.LogError (www.error);
yield return null;
}
else
{
ab = www.assetBundle;
GetObject ( ab, assetName, type, callBack, isUnload); if (!isUnload)
{
if (!assetBundleRefDic.ContainsKey(url))
{
Debug.Log("add");
assetBundleRefDic.Add(url, ab);
}
}
}
}
} //从 AssetBundle 中将资源加载出来
private void GetObject(AssetBundle ab, string assetName, Type type, CallBack callBack, bool isUnload)
{
UnityEngine.Object obj = ab.LoadAsset (assetName, type); if (callBack != null)
{
callBack(obj); // 回调
} if (isUnload) {
// 加载资源后从内存中卸载
ab.Unload (true);
}
} //根据地址从字典中获取 AssetBundle
private AssetBundle GetASFromUrl(string url)
{
AssetBundle ab = null;
if (assetBundleRefDic.TryGetValue (url, out ab)) {
return ab;
} return null;
}
}
//调用如下

using UnityEngine;
using System.Collections; public class Test : MonoBehaviour { // Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.A))
{
string loadPath = "Android/allassets/gameobject.unity3d";
string asName = "gameobject";
StartCoroutine(LoadAssetBundle.Instance.Load(loadPath, asName, typeof(GameObject), CallBack, true));
} if (Input.GetKeyDown (KeyCode.D))
{
string loadPath = "Android/allassets/gameobject.unity3d";
string asName = "gameobject";
StartCoroutine(LoadAssetBundle.Instance.Load(loadPath, asName, typeof(GameObject), CallBack, false));
}
} private void CallBack(UnityEngine.Object obj)
{
Debug.Log (obj.name);
GameObject.Instantiate ((GameObject)obj);
}
}

Unity5 AssetBundle 打包以及加载的更多相关文章

  1. &lbrack;Unity&rsqb; unity5&period;3 assetbundle打包及加载

    Unity5.3更新了assetbundle的打包和加载api,下面简单介绍使用方法及示例代码. 在Unity中选中一个prefab查看Inspector窗口,有两个位置可以进行assetbundle ...

  2. Unity3d 5&period;x AssetBundle打包与加载

    1.AssetBundle打包 unity 5.x版本AssetBundle打包,只需要设置好AssetBundle的名称后,unity会自动将其打包,无需处理其他,唯独需要做的是设置好个AssetB ...

  3. Unity5 AssetBundle系列——资源加载卸载以及AssetBundleManifest的使用

    下面代码列出了对于assetbundle资源的常用操作,其中有针对bundle.asset.gameobject三种类型对象的操作,实际使用中尽量保证成对使用. 这一块的操作比较繁琐,但只要使用正确, ...

  4. Unity5 AssetBundle打包加载及服务器加载

    Assetbundle为资源包不是资源 打包1:通过脚本指定打包 AssetBundleBuild ab = new AssetBundleBuild                         ...

  5. AssetBundle资源打包与加载

    AssetBundle资源打包  1.AssetLabels资源标签 文件名:资源打包成AssetBundle后的文件名,类似于压缩包的名字 后缀:自定义 文件名和后缀名都是小写格式(大写会自动转为小 ...

  6. unity中ScriptableObject在assetbundle中的加载

    转载请标明出处:http://www.cnblogs.com/zblade/ 以前都是写一些个人的调研博客,从今天开始,也写一些个人在开发中遇到的一些可以分享的趟坑博客,为后续的开发人员提供一些绵薄之 ...

  7. Assetbundle管理与加载

    最近在做项目优化的时候发现公司的项目用的还是老式的WWW去加载assetbundle资源的形式,而且是通过在两个Update里面分开加载AB和Asset的,这样虽然避免了协程的的使用,但是把一件事分开 ...

  8. Assetbundle创建与加载

    [Assetbundle创建与加载] Unity有两种动态加载机制:一种是Resource.Load.一种是AssetBundle.Assetbundle是Unity Pro提供的功能,它可以把多个游 ...

  9. Unity3D AssetBundle的打包与加载

    在Unity项目开发过程中,当要做热更新时常常使用一个叫做AssetBundle的东西,这里做一点个人的学习记录 步骤1: 设置打包标签:具体步骤----进入Unity,选择某一资源然后看右下角,在那 ...

随机推荐

  1. React Native 使用问题记录

    1.<View></View>之间有空格会报错 Trying to add unknown view tag 2.一些js语法糖注意点http://facebook.githu ...

  2. group&lowbar;concat函数使用

    t1表 语句: select type,group_concat(name) from t1 group by type 结果

  3. IO流&lpar;五&rpar;&lowbar;&lowbar;文件的递归、Properties、打印流PrintStream与PrintWriter、序列流SequenceInputStream

    一.文件的遍历 1.需求:对指定目录进行所有的内容的列出(包含子目录的内容)-文件的深度遍历 思想:递归的思想,在递归的时候要记住递归的层次. public class FileTest { publ ...

  4. &lbrack;转&rsqb;jquery 对 Json 的各种遍历

    原文地址:http://caibaojian.com/jquery-each-json.html 概述 JSON(javascript Object Notation) 是一种轻量级的数据交换格式,采 ...

  5. Java设计模式——组合模式

    JAVA 设计模式 组合模式 用途 组合模式 (Component) 将对象组合成树形结构以表示“部分-整体”的层次结构.组合模式使得用户对单个对象和组合对象的使用具有唯一性. 组合模式是一种结构型模 ...

  6. 无法Debug SQL&colon; Unable to start T-SQL Debugging&period; Could not attach to SQL Server process on

    今天SSMS debug SQL当脚本,突然错误: Unable to start T-SQL Debugging. Could not attach to SQL Server process on ...

  7. 测试驱动开发实践5————testSave之修改文档分类

    [内容指引] 1.确定"修改文档分类"的微服务接口及所需的参数 2.设计测试用例及测试用例合并 3.为测试用例赋值并驱动开发 上一篇我们通过17个测试用例完成了"新增文档 ...

  8. idea src下源文件和class编译文件不一致

    今天遇到一个神奇BUG,一个和elasticsearch没有任何关系的项目,报错ES某个包找不到,刚开始以为是依赖了父项目的某个包,并且本项目主启动类ComponentScan扫描了相关的类进入Spr ...

  9. Laravel Cache 缓存钉钉微应用的 Access Token

    钉钉微应用的 Access token 如何获取? Access_Token 是企业访问钉钉开放平台全局接口的唯一凭证,即调用接口时需携带Access_Token.从接口列表看,所有接口都需要携带 a ...

  10. c&plus;&plus; std&colon;&colon;function

    std::function 是一个模板类,用于封装各种类似于函数这样的对象,例如普通函数,仿函数,匿名函数等等.其强大的多态能力,让其使用只依赖于调用特征.在程序的升级中,可以实现一个调用表,以兼容新 ...