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

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

  1. // C# Example
  2. // Builds an asset bundle from the selected objects in the project view.
  3. // Once compiled go to "Menu" -> "Assets" and select one of the choices
  4. // to build the Asset Bundle
  5.  
  6. using UnityEngine;
  7. using UnityEditor;
  8. using System.IO;
  9. public class ExportAssetBundles {
  10. [MenuItem("Assets/Build AssetBundle Binary file From Selection - Track dependencies ")]
  11. static void ExportResource () {
  12. // Bring up save panel
  13. string path = EditorUtility.SaveFilePanel ("Save Resource", "", "New Resource", "unity3d");
  14. if (path.Length != ) {
  15. // Build the resource file from the active selection.
  16. Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
  17. BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path, BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets);
  18. Selection.objects = selection;
  19.  
  20. FileStream fs = new FileStream(path,FileMode.Open,FileAccess.ReadWrite);
  21. byte[] buff = new byte[fs.Length+];
  22. fs.Read(buff,,(int)fs.Length);
  23. buff[buff.Length-] = ;
  24. fs.Close();
  25. File.Delete(path);
  26.  
  27. string BinPath = path.Substring(,path.LastIndexOf('.'))+".bytes";
  28. // FileStream cfs = new FileStream(BinPath,FileMode.Create);
  29. cfs.Write(buff,,buff.Length);
  30. buff =null;
  31. cfs.Close();
  32.  
  33. // string AssetsPath = BinPath.Substring(BinPath.IndexOf("Assets"));
  34. // Object ta = AssetDatabase.LoadAssetAtPath(AssetsPath,typeof(Object));
  35. // BuildPipeline.BuildAssetBundle(ta, null, path);
  36. }
  37. }
  38. [MenuItem("Assets/Build AssetBundle From Selection - No dependency tracking")]
  39. static void ExportResourceNoTrack () {
  40. // Bring up save panel
  41. string path = EditorUtility.SaveFilePanel ("Save Resource", "", "New Resource", "unity3d");
  42. if (path.Length != ) {
  43. // Build the resource file from the active selection.
  44. BuildPipeline.BuildAssetBundle(Selection.activeObject, Selection.objects, path);
  45. }
  46. }

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

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

  1. using UnityEngine;
  2. using System.Collections;
  3. using System;
  4.  
  5. public class WWWLoadTest : MonoBehaviour
  6. {
  7.  
  8. public string BundleURL;
  9. public string AssetName;
  10. IEnumerator Start()
  11. {
  12. WWW www =WWW.LoadFromCacheOrDownload(BundleURL,);
  13.  
  14. yield return www;
  15.  
  16. TextAsset txt = www.assetBundle.Load("characters",typeof(TextAsset)) as TextAsset;
  17.  
  18. byte[] data = txt.bytes;
  19.  
  20. byte[] decryptedData = Decryption(data);
  21. Debug.LogError("decryptedData length:"+decryptedData.Length);
  22. StartCoroutine(LoadBundle(decryptedData));
  23. }
  24.  
  25. IEnumerator LoadBundle(byte[] decryptedData){
  26. AssetBundleCreateRequest acr = AssetBundle.CreateFromMemory(decryptedData);
  27. yield return acr;
  28. AssetBundle bundle = acr.assetBundle;
  29. Instantiate(bundle.Load(AssetName));
  30.  
  31. }
  32.  
  33. byte[] Decryption(byte[] data){
  34. byte[] tmp = new byte[data.Length-];
  35. for(int i=;i<data.Length-;i++){
  36. tmp[i] = data[i];
  37. }
  38. return tmp;
  39.  
  40. }
  41.  
  42. }

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格式,解析,然后变资源

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

  1. using UnityEngine;
  2. using System.Collections;
  3. using UnityEditor;
  4. using System.IO;
  5.  
  6. public class assetPack : Editor
  7. {
  8. //打包单个
  9. [MenuItem("Custom Editor/Create AssetBunldes Main")]
  10. static void CreateAssetBunldesMain ()
  11. {
  12. //获取在Project视图中选择的所有游戏对象
  13. Object[] SelectedAsset = Selection.GetFiltered (typeof(Object), SelectionMode.DeepAssets);
  14.  
  15. //遍历所有的游戏对象
  16. foreach (Object obj in SelectedAsset)
  17. {
  18. //本地测试:建议最后将Assetbundle放在StreamingAssets文件夹下,如果没有就创建一个,因为移动平台下只能读取这个路径
  19. //StreamingAssets是只读路径,不能写入
  20. //服务器下载:就不需要放在这里,服务器上客户端用www类进行下载。
  21. string targetPath = Application.dataPath + "/StreamingAssets/" + obj.name + ".assetbundle";
  22. if (BuildPipeline.BuildAssetBundle (obj, null, targetPath, BuildAssetBundleOptions.CollectDependencies)) {
  23. Debug.Log(obj.name +"资源打包成功");
  24. }
  25. else
  26. {
  27. Debug.Log(obj.name +"资源打包失败");
  28. }
  29. }
  30. //刷新编辑器
  31. AssetDatabase.Refresh ();
  32.  
  33. }
  34.  
  35. [MenuItem("Custom Editor/Create AssetBunldes ALL")]
  36. static void CreateAssetBunldesALL ()
  37. {
  38.  
  39. Caching.CleanCache ();
  40.  
  41. string Path = Application.dataPath + "/StreamingAssets/ALL.assetbundle";
  42.  
  43. Object[] SelectedAsset = Selection.GetFiltered (typeof(Object), SelectionMode.DeepAssets);
  44.  
  45. foreach (Object obj in SelectedAsset)
  46. {
  47. Debug.Log ("Create AssetBunldes name :" + obj);
  48. }
  49.  
  50. //这里注意第二个参数就行
  51. if (BuildPipeline.BuildAssetBundle (null, SelectedAsset, Path, BuildAssetBundleOptions.CollectDependencies)) {
  52. AssetDatabase.Refresh ();
  53. } else
  54. {
  55.  
  56. }
  57. }
  58.  
  59. [MenuItem("Custom Editor/Create Scene")]
  60. static void CreateSceneALL ()
  61. {
  62. //清空一下缓存
  63. Caching.CleanCache();
  64. string Path = Application.dataPath + "/eScene.unity3d";
  65. string[] levels = { "Assets/myScene.unity" };
  66. //打包场景
  67. BuildPipeline.BuildPlayer( levels, Path,BuildTarget.StandaloneWindows, BuildOptions.BuildAdditionalStreamedScenes);
  68. AssetDatabase.Refresh ();
  69. }
  70.  
  71. [MenuItem("Custom Editor/Save Scene")]
  72. static void ExportScene()
  73. {
  74. // 打开保存面板,获得用户选择的路径
  75. string path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "unity3d");
  76.  
  77. if (path.Length != )
  78. {
  79. // 选择的要保存的对象
  80. Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
  81. string[] scenes = { "Assets/myScene.unity" };
  82. //打包
  83. BuildPipeline.BuildPlayer(scenes, path, BuildTarget.StandaloneWindows, BuildOptions.BuildAdditionalStreamedScenes);
  84. }
  85. AssetDatabase.Refresh();
  86. }
  87. [MenuItem("Custom Editor/Save Scene2")]
  88. static void ExportResource()
  89. {
  90. // Bring up save panel
  91. string path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "unity3d");
  92. if (path.Length != )
  93. {
  94. // Build the resource file from the active selection.
  95. Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
  96. BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path,
  97. BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets);
  98. Selection.objects = selection;
  99. }
  100. }
  101.  
  102. [MenuItem("Custom Editor/Build AssetBundle From Selection - Track dependencies")]
  103. static void ExportResource2()
  104. {
  105. // Bring up save panel
  106. string path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "unity3d");
  107. if (path.Length != )
  108. {
  109. // Build the resource file from the active selection.
  110. Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
  111. BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path,
  112. BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets);
  113. Selection.objects = selection;
  114. }
  115. }
  116.  
  117. [MenuItem("Custom Editor/Build AssetBundle Complited to bytes")]
  118. static void ExportResource5()
  119. {
  120. // Bring up save panel
  121. string path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "unity3d");
  122. if (path.Length != )
  123. {
  124. // Build the resource file from the active selection.
  125. Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
  126. BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path,
  127. BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets, BuildTarget.StandaloneWindows);
  128. Selection.objects = selection;
  129.  
  130. FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
  131. byte[] buff = new byte[fs.Length + ];
  132. fs.Read(buff, , (int)fs.Length);
  133. buff[buff.Length - ] = ;
  134. Debug.Log("filelength:"+ buff.Length);
  135. fs.Close();
  136. File.Delete(path);
  137.  
  138. string BinPath = path.Substring(, path.LastIndexOf('.')) + ".bytes";
  139. FileStream cfs = new FileStream(BinPath,FileMode.Create);
  140. cfs.Write(buff, , buff.Length);
  141. Debug.Log("filelength:" + buff.Length);
  142. buff = null;
  143. cfs.Close();
  144.  
  145. }
  146. }
  147.  
  148. [MenuItem("Custom Editor/Build AssetBundle From Selection Twice")]
  149. static void ExportResourceNoTrack()
  150. {
  151. // Bring up save panel
  152. string path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "unity3d");
  153. if (path.Length != )
  154. {
  155. // Build the resource file from the active selection.
  156. BuildPipeline.BuildAssetBundle(Selection.activeObject, Selection.objects, path);
  157. }
  158. }
  159. }

加载部分

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class loadnew : MonoBehaviour
  5. {
  6. public string filename;
  7. private string BundleURL;
  8. private string AssetName;
  9. IEnumerator Start()
  10. {
  11. BundleURL = "file://" + Application.dataPath +"/"+ filename+".unity3d";
  12. Debug.Log("path:"+ BundleURL);
  13. WWW m_Download = new WWW(BundleURL);
  14.  
  15. yield return m_Download;
  16. if (m_Download.error != null)
  17. {
  18. // Debug.LogError(m_Download.error);
  19. Debug.Log("Warning errow: " + "NewScene");
  20. yield break;
  21. }
  22.  
  23. TextAsset txt = m_Download.assetBundle.Load(filename, typeof(TextAsset)) as TextAsset;
  24. byte[] data = txt.bytes;
  25.  
  26. byte[] decryptedData = Decryption(data);
  27. Debug.Log("decryptedData length:" + decryptedData.Length);
  28. StartCoroutine(LoadBundle(decryptedData));
  29. }
  30.  
  31. IEnumerator LoadBundle(byte[] decryptedData)
  32. {
  33. AssetBundleCreateRequest acr = AssetBundle.CreateFromMemory(decryptedData);
  34. yield return acr;
  35. AssetBundle bundle = acr.assetBundle;
  36. Instantiate(bundle.mainAsset);
  37.  
  38. }
  39.  
  40. byte[] Decryption(byte[] data)
  41. {
  42. byte[] tmp = new byte[data.Length - ];
  43. for (int i = ; i < data.Length - ; i++)
  44. {
  45. tmp[i] = data[i];
  46. }
  47. return tmp;
  48.  
  49. }
  50.  
  51. void update()
  52. {
  53.  
  54. }
  55. }

u3d外部资源加载加密的更多相关文章

  1. Android应用安全之外部动态加载DEX文件风险

    1. 外部动态加载DEX文件风险描述 Android 系统提供了一种类加载器DexClassLoader,其可以在运行时动态加载并解释执行包含在JAR或APK文件内的DEX文件.外部动态加载DEX文件 ...

  2. 再谈DOMContentLoaded与渲染阻塞—分析html页面事件与资源加载

    浏览器的多线程中,有的线程负责加载资源,有的线程负责执行脚本,有的线程负责渲染界面,有的线程负责轮询.监听用户事件. 这些线程,根据浏览器自身特点以及web标准等等,有的会被浏览器特意的阻塞.两个很明 ...

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

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

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

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

  5. Laya资源加载小记

    Laya.Loader负责资源的加载逻辑,被LoaderManager管理. Laya支持多种类型资源加载,也支持自定义类型加载.不同类型的加载方式可能不同. Laya.Loader缓存已经被加载过得 ...

  6. 通过源码浅析Java中的资源加载

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

  7. 细谈unity资源加载和卸载

    转载请标明出处:http://www.cnblogs.com/zblade/ 一.概要 在了解unity的资源管理方式之后,接下来细谈一下Unity的资源是如何从磁盘中加载到运行时的内存中,以及又是如 ...

  8. 简说Spring中的资源加载

    声明: 本文若有 任何纰漏.错误,请不吝指正!谢谢! 问题描述 遇到一个关于资源加载的问题,因此简单的记录一下,对Spring资源加载也做一个记录. 问题起因是使用了@PropertySource来进 ...

  9. High Performance Networking in Google Chrome 进程间通讯(IPC) 多进程资源加载

    小结: 1. 小文件存储于一个文件中: 在内部,磁盘缓存(disk cache)实现了它自己的一组数据结构, 它们被存储在一个单独的缓存目录里.其中有索引文件(在浏览器启动时加载到内存中),数据文件( ...

随机推荐

  1. LeetCode: Merge k Sorted Lists 解题报告

    Merge k Sorted Lists Merge k sorted linked lists and return it as one sorted list. Analyze and descr ...

  2. 【Python学习笔记】-冒泡排序、插入排序、二分法查找

    原文出处:https://blog.csdn.net/yort2016/article/details/68065728 冒泡排序 主要是拿一个数与列表中所有的数进行比对,若比此数大(或者小),就交换 ...

  3. Highcharts 多个Y轴动态刷新数据

    效果图: js代码: $(function() { $(document).ready(function() { Highcharts.setOptions({ global: { useUTC: f ...

  4. Linux给tomcat指定jdk

    在安装jenkins的时候,发现必须是jdk1.8,所以就只能单独安装一个tomcat,在给tomcat配置jdk1.8了,以免破坏以前的项目 安装就不多说了.这里需要修改两个配置文件: 安装的tom ...

  5. [转]【MySQL】关于时间的查询,比如本月,本年,本季度

    原文地址:https://www.cnblogs.com/flydkPocketMagic/p/7089324.html -- mysql查询本季度 -- 今天 select * from ticke ...

  6. [转]httpclient编码

    这几天都在纠结Java Web开发中的中文编码问题.其实,很多Java Web开发者都被中文编码“折磨”过,网络上有大量的讨论.以前我也读过这方面的博文,读完后感觉似乎懂了,好像知道了编码问题的原因和 ...

  7. 实践 ArcGIS Web 3D

    ArcGIS 产品家族的 Web 3D 功能众多用户期待已久.从 ArcGIS 10.3.1 版本号開始,Esri 放了个大招,千呼万唤始出来的 Web 3D 功能,最终不再犹抱琵琶半遮面了. 那究竟 ...

  8. Java之线程状态

    Java线程有6种状态: 1.New(新生),使用new Thread(r)创建一个新线程时,该线程处于新生状态,新生状态会为线程的执行做一些准备. 2.Runnable(可执行),调用线程的star ...

  9. Unity2017与Visual Studio2017的兼容问题

    Unity2017中新建脚本后,用Visual Studio2017打开发现不兼容. 方法一:管理员权限运行Unity. 方法二:打开Visual Studio Installer,下载Unity相关 ...

  10. Linux 系统位数以及 Linux 软件位数查看

    一. Linux系统位数查看: getconf LONG_BIT uname -a 二. 软件位数查看: file ....txt ![](https://images2018.cnblogs.com ...