原文地址:http://www.cnblogs.com/88999660/archive/2013/04/10/3011912.html

首先要鄙视下unity3d的文档编写人员极度不负责任,到发帖为止依然没有更新正确的示例代码。

// C# Example// Builds an asset bundle from the selected objects in the project view.// Once compiled go to "Menu" -> "Assets" and select one of the choices// to build the Asset Bundleusing UnityEngine;using UnityEditor;using System.IO;public class ExportAssetBundles {[MenuItem("Assets/Build AssetBundle Binary file From Selection - Track dependencies ")]static void ExportResource () {// Bring up save panelstring path = EditorUtility.SaveFilePanel ("Save Resource", "", "New Resource", "unity3d");if (path.Length != 0) {// Build the resource file from the active selection.Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path, BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets);Selection.objects = selection;FileStream fs = new FileStream(path,FileMode.Open,FileAccess.ReadWrite);byte[] buff = new byte[fs.Length+1];fs.Read(buff,0,(int)fs.Length);buff[buff.Length-1] = 0;fs.Close();File.Delete(path);string BinPath = path.Substring(0,path.LastIndexOf('.'))+".bytes";//             FileStream cfs = new FileStream(BinPath,FileMode.Create);cfs.Write(buff,0,buff.Length);buff =null;cfs.Close();//              string AssetsPath = BinPath.Substring(BinPath.IndexOf("Assets"));
//              Object ta = AssetDatabase.LoadAssetAtPath(AssetsPath,typeof(Object));
//              BuildPipeline.BuildAssetBundle(ta, null, path);
            }}[MenuItem("Assets/Build AssetBundle From Selection - No dependency tracking")]static void ExportResourceNoTrack () {// Bring up save panelstring path = EditorUtility.SaveFilePanel ("Save Resource", "", "New Resource", "unity3d");if (path.Length != 0) {// Build the resource file from the active selection.
                BuildPipeline.BuildAssetBundle(Selection.activeObject, Selection.objects, path);}}

  把打包的文件转换成了binary文件并多加了一个字节加密。

  当bytes文件生成好后再选中它,使用"Assets/Build AssetBundle From Selection - No dependency tracking"再次打包。

using UnityEngine;
using System.Collections;
using System;public class WWWLoadTest : MonoBehaviour
{public string BundleURL;public string AssetName;IEnumerator Start(){WWW www =WWW.LoadFromCacheOrDownload(BundleURL,2);yield return www;TextAsset txt = www.assetBundle.Load("characters",typeof(TextAsset)) as TextAsset;byte[]  data = txt.bytes;byte[] decryptedData = Decryption(data);Debug.LogError("decryptedData length:"+decryptedData.Length);StartCoroutine(LoadBundle(decryptedData));}IEnumerator LoadBundle(byte[] decryptedData){        AssetBundleCreateRequest acr = AssetBundle.CreateFromMemory(decryptedData);            yield return acr;AssetBundle bundle = acr.assetBundle;        Instantiate(bundle.Load(AssetName));}byte[] Decryption(byte[] data){byte[] tmp = new byte[data.Length-1];for(int i=0;i<data.Length-1;i++){tmp[i] = data[i];    }return tmp;}}

WWW.LoadFromCacheOrDownload的作用就是下载并缓存资源,要注意后面的版本号参数,如果替换了资源却没有更新版本号,客户端依然会加载缓存中的文件。

www.assetBundle.Load("characters",typeof(TextAsset)) as TextAsset  //characters是加密文件的名字

AssetBundleCreateRequest acr = AssetBundle.CreateFromMemory(decryptedData);

这句是官网最坑爹的,AssetBundle.CreateFromMemory明 明返回的是AssetBundleCreateRequest官网却写得是AssetBundle,而且 AssetBundleCreateRequest是一个异步加载,必须用协程的方式加载官网也没有提到。跟多兄弟就倒在了这里

完。

原理这里要说明下,是这样子的,先把资源变成。unity3d格式,然后转成。bytes格式,再转成。unity3d格式,

加载的时候加载。unity3d格式,解析,然后变资源

我经过测试给出我的代码:

using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;public class assetPack : Editor
{
//打包单个
[MenuItem("Custom Editor/Create AssetBunldes Main")]
static void CreateAssetBunldesMain ()
{//获取在Project视图中选择的所有游戏对象Object[] SelectedAsset = Selection.GetFiltered (typeof(Object), SelectionMode.DeepAssets);//遍历所有的游戏对象foreach (Object obj in SelectedAsset){//本地测试:建议最后将Assetbundle放在StreamingAssets文件夹下,如果没有就创建一个,因为移动平台下只能读取这个路径//StreamingAssets是只读路径,不能写入//服务器下载:就不需要放在这里,服务器上客户端用www类进行下载。string targetPath = Application.dataPath + "/StreamingAssets/" + obj.name + ".assetbundle";if (BuildPipeline.BuildAssetBundle (obj, null, targetPath, BuildAssetBundleOptions.CollectDependencies)) {Debug.Log(obj.name +"资源打包成功");}else{Debug.Log(obj.name +"资源打包失败");}}//刷新编辑器
    AssetDatabase.Refresh ();  }[MenuItem("Custom Editor/Create AssetBunldes ALL")]
static void CreateAssetBunldesALL ()
{Caching.CleanCache ();string Path = Application.dataPath + "/StreamingAssets/ALL.assetbundle";Object[] SelectedAsset = Selection.GetFiltered (typeof(Object), SelectionMode.DeepAssets);foreach (Object obj in SelectedAsset){Debug.Log ("Create AssetBunldes name :" + obj);}//这里注意第二个参数就行if (BuildPipeline.BuildAssetBundle (null, SelectedAsset, Path, BuildAssetBundleOptions.CollectDependencies)) {AssetDatabase.Refresh ();} else{}
}[MenuItem("Custom Editor/Create Scene")]
static void CreateSceneALL ()
{//清空一下缓存
    Caching.CleanCache();string Path = Application.dataPath + "/eScene.unity3d";string[] levels = { "Assets/myScene.unity" };//打包场景
    BuildPipeline.BuildPlayer( levels, Path,BuildTarget.StandaloneWindows, BuildOptions.BuildAdditionalStreamedScenes);AssetDatabase.Refresh ();
}[MenuItem("Custom Editor/Save Scene")]
static void ExportScene()
{// 打开保存面板,获得用户选择的路径  string path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "unity3d");if (path.Length != 0){// 选择的要保存的对象  Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);string[] scenes = { "Assets/myScene.unity" };//打包
        BuildPipeline.BuildPlayer(scenes, path, BuildTarget.StandaloneWindows, BuildOptions.BuildAdditionalStreamedScenes);}AssetDatabase.Refresh();
}
[MenuItem("Custom Editor/Save Scene2")]
static void ExportResource()
{// Bring up save panelstring path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "unity3d");if (path.Length != 0){// Build the resource file from the active selection.Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path,BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets);Selection.objects = selection;}
}[MenuItem("Custom Editor/Build AssetBundle From Selection - Track dependencies")]
static void ExportResource2()
{// Bring up save panelstring path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "unity3d");if (path.Length != 0){// Build the resource file from the active selection.Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path,BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets);Selection.objects = selection;}
}[MenuItem("Custom Editor/Build AssetBundle Complited  to  bytes")]
static void ExportResource5()
{// Bring up save panelstring path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "unity3d");if (path.Length != 0){// Build the resource file from the active selection.Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path,BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets, BuildTarget.StandaloneWindows);Selection.objects = selection;FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);byte[] buff = new byte[fs.Length + 1];fs.Read(buff, 0, (int)fs.Length);buff[buff.Length - 1] = 0;Debug.Log("filelength:"+ buff.Length);fs.Close();File.Delete(path);string BinPath = path.Substring(0, path.LastIndexOf('.')) + ".bytes";FileStream cfs = new FileStream(BinPath,FileMode.Create);cfs.Write(buff, 0, buff.Length);Debug.Log("filelength:" + buff.Length);buff = null;cfs.Close();}
}[MenuItem("Custom Editor/Build AssetBundle From Selection Twice")]
static void ExportResourceNoTrack()
{// Bring up save panelstring path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "unity3d");if (path.Length != 0){// Build the resource file from the active selection.
        BuildPipeline.BuildAssetBundle(Selection.activeObject, Selection.objects, path);}
}
}

加载部分

using UnityEngine;
using System.Collections;public class loadnew : MonoBehaviour
{public string filename;private string BundleURL;private string AssetName;IEnumerator Start(){BundleURL = "file://" + Application.dataPath +"/"+ filename+".unity3d";Debug.Log("path:"+ BundleURL);WWW m_Download = new WWW(BundleURL);yield return m_Download;if (m_Download.error != null){//   Debug.LogError(m_Download.error);Debug.Log("Warning errow: " + "NewScene");yield break;}TextAsset txt = m_Download.assetBundle.Load(filename, typeof(TextAsset)) as TextAsset;byte[] data = txt.bytes;byte[] decryptedData = Decryption(data);Debug.Log("decryptedData length:" + decryptedData.Length);StartCoroutine(LoadBundle(decryptedData));}IEnumerator LoadBundle(byte[] decryptedData){AssetBundleCreateRequest acr = AssetBundle.CreateFromMemory(decryptedData);yield return acr;AssetBundle bundle = acr.assetBundle;Instantiate(bundle.mainAsset);}byte[] Decryption(byte[] data){byte[] tmp = new byte[data.Length - 1];for (int i = 0; i < data.Length - 1; i++){tmp[i] = data[i];}return tmp;}void update(){}
}

u3d外部资源加载加密相关推荐

  1. 浏览器页面资源加载过程与优化

    评价页面性能好坏的核心之一就是页面的加载速度,而页面加载速度的关键就是页面资源的加载.本文将从浏览器浏览器页面资源加载过程展开分析,来引出页面关键请求路径的概念,并给出如何优化该关键请求路径的一些方法 ...

  2. Spring资源加载器抽象和缺省实现 -- ResourceLoader + DefaultResourceLoader(摘)

    概述 对于每一个底层资源,比如文件系统中的一个文件,classpath上的一个文件,或者一个以URL形式表示的网络资源,Spring 统一使用 Resource 接口进行了建模抽象,相应地,对于这些资 ...

  3. Android apk动态加载机制的研究(二):资源加载和activity生命周期管理

    转载请注明出处:http://blog.csdn.net/singwhatiwanna/article/details/23387079 (来自singwhatiwanna的csdn博客) 前言 为了 ...

  4. unity 异步加载网络图片_一个非常好用的AssetBundle资源加载器

    Loxodon Framework Bundle是一个非常好用的AssetBundle加载器,也是一个AssetBundle冗余分析工具.它能够自动管理AssetBundle之间复杂的依赖关系,它通过 ...

  5. composition java_阿里P7架构师通过源码浅析Java中的资源加载

    一. 前提 最近在做一个基础组件项目刚好需要用到JDK中的资源加载,这里说到的资源包括类文件和其他静态资源,刚好需要重新补充一下类加载器和资源加载的相关知识,整理成一篇文章. 二. 什么是类加载器 虚 ...

  6. 浏览器了解(五)资源加载顺序

    资源加载顺序 在加载web资源时,首先下载html文件,进行html解析,在遇到javascript或css标签时,启动相应的解析机处理. 当遇到外部资源时(如<script src='xxx' ...

  7. 【Unity3D日常开发】Unity中的资源加载与文件路径

    推荐阅读 CSDN主页 GitHub开源地址 Unity3D插件分享 简书地址 我的个人博客 QQ群:1040082875 大家好,我是佛系工程师☆恬静的小魔龙☆,不定时更新Unity开发技巧,觉得有 ...

  8. Unity游戏开发——新发教你做游戏(三):3种资源加载方式

    文章目录 一.前言 二.Unity的目录结构规范 1.Resources(不是很推荐把资源放这个目录) 2.RawAssets(存放生资源) 3.GameRes(存放熟资源) 4.StreamingA ...

  9. JavaScript 页面资源加载:onload,onerror

    资源加载:onload,onerror 浏览器允许我们跟踪外部资源的加载 -- 脚本,iframe,图片等. 这里有两个事件: onload -- 成功加载, onerror -- 出现 error. ...

最新文章

  1. java鼠标事件获得键盘值_请问JAVA怎么模拟鼠标和键盘事件[200分]
  2. HTML5移动应用开发入门经典 中文pdf扫描版
  3. Maven快速创建SpringMVC web(1)
  4. c++:opencv读图后mat矩阵的基本操作
  5. python的列表和元组
  6. javaTemplates-学习笔记四
  7. Think in Java第四版 读书笔记1
  8. onchange监听input值变化及input隐藏后change事件不触发的原因与解决方法(设置readonly后onchange不起作用的解决方案)
  9. MySQL: ERROR13(HY000):Can't get stat of的问题
  10. Bailian4138 POJ NOI MATH-7827 质数的和与积【数论】
  11. linux基础(一)——切换到root用户和普通用户
  12. 高德地图入驻广州交警 实现“互联网+交通”无缝对接
  13. MvvmCross框架在XamarinForms中的使用入门
  14. 天宫管理系统_天宫职位
  15. 亲戚关系关系算法java程序_并查集1——查找亲戚关系
  16. 1413 权势二进制
  17. 介绍两个用于生成二维码的js库
  18. python学习笔记分享(四十)网络爬虫(7)反爬虫问题,解决中文乱码,登陆和验证码处理
  19. 闭合导线的近似平均差(工程测量)
  20. 【“计算机科学与技术”专业小白成长系列】Linux Shell 编程 极简教程

热门文章

  1. “send“ and “transfer“ are only available for objects of type “address payable“, not “address
  2. php 文件 计数,文件计数问题
  3. 光机学院计算机系,计算机系召开第十二届科技节闭幕式
  4. Java中各种引用(Reference)解析
  5. mongodb----副本集搭建及故障自动切换
  6. jmeter接口测试----8用户定义的变量
  7. karaf中利用Bundle引入外部log4j配置文件
  8. ※归并排序(merge sort)
  9. JAVA设计模式之【外观模式】
  10. MEF实现设计上的“松耦合”(一)