原文地址: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 Bundle using 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 panel
string path = EditorUtility.SaveFilePanel ("Save Resource", "", "New Resource", "unity3d");
if (path.Length != ) {
// 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+];
fs.Read(buff,,(int)fs.Length);
buff[buff.Length-] = ;
fs.Close();
File.Delete(path); string BinPath = path.Substring(,path.LastIndexOf('.'))+".bytes";
// FileStream cfs = new FileStream(BinPath,FileMode.Create);
cfs.Write(buff,,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 panel
string path = EditorUtility.SaveFilePanel ("Save Resource", "", "New Resource", "unity3d");
if (path.Length != ) {
// 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,); 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-];
for(int i=;i<data.Length-;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 != )
{
// 选择的要保存的对象
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 panel
string path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "unity3d");
if (path.Length != )
{
// 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 panel
string path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "unity3d");
if (path.Length != )
{
// 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 panel
string path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "unity3d");
if (path.Length != )
{
// 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 + ];
fs.Read(buff, , (int)fs.Length);
buff[buff.Length - ] = ;
Debug.Log("filelength:"+ buff.Length);
fs.Close();
File.Delete(path); string BinPath = path.Substring(, path.LastIndexOf('.')) + ".bytes";
FileStream cfs = new FileStream(BinPath,FileMode.Create);
cfs.Write(buff, , 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 panel
string path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "unity3d");
if (path.Length != )
{
// 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 - ];
for (int i = ; i < data.Length - ; i++)
{
tmp[i] = data[i];
}
return tmp; } void update()
{ }
}

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. source activate my_env 失败,source not found

    今天连接到服务器后,安装anaconda.虽然在安装过程中选择将anaconda加入到系统变量中去.而且在 ~/.bashrc 中确实有 export PATH="/home/xnh/ana ...

  2. myeclipse上传git的问题

    unstaged changes 建好仓库,连接到git之后,在上传代码的时候发现有一些代码是unstaged changes状态.这样的文件是没法上传到git上去的.解决方法是给这些文件增加inde ...

  3. TextView

    wrap_content 设置TextView的宽度和高度为 wrap_content,则其大小会自动适应文本. textSize 设置字体大小 textColor 设置字体颜色 <TextVi ...

  4. iOS App中第一次运行添加半透明新手指引

    实现方式: 在当前View上一个蒙层,然后找出需要标记的地方圈为白色,那些箭头和提示文字都是UI做出来的图上自带的. 代码: 判断是第一次运行APP后进入页面调用 -(void)newGuide { ...

  5. linux下mysql重置密码并且远程可以访问

    .重置mysql密码: 杀死所有的yum myql进程: pkill mysql; 查看端口 netstat 端口号杀死) 修改my.cnf文件,在[mysqld]下加入skip-grant-tabl ...

  6. 用Total Commander for Android管理应用程序

    用Total Commander for Android管理应用程序 前不久安装了一个Total Commander的Anroid版本,除了用它来管理文件之外,我发现用它管理已安装程序挺不错的. 可以 ...

  7. eclipse mars 4.5.1 自定义工具栏

    window>>perspective>>Customize Perspective

  8. 在IIS中访问APS页面时提示:“最可能的原因使用的托管的处理程序,但是未安装或未完整安装asp.net“

    打开CMD窗口,执行下面的命令: "%WINDIR%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe" -iru -ena ...

  9. 在Word 2007中添加参考文献及其引用的方法

    以前写文章的时候忽略了在文章中添加参考文献及其引用的方式,文章各式显得不太正式,在网上进行了相关搜索,将方法整理如下: 1.将光标停留在需要插入文献的地方[1],选择菜单栏上的"引用 -&g ...

  10. LVS的优点和缺点

    LVS的优点是:1.抗负载能力强.是工作在网络4层之上仅作分发之用,没有流量的产生,这个特点也决定了它在负载均衡软件里的性能最强的,对内存和cpu资源消耗比较低.2.配置性比较低,这是一个缺点也是一个 ...