1.打包
新建工程,并新建场景,场景里放个Cube并做成prefab,再随便放几个东西,保存场景。
新建文件夹命名为Editor,一定要起这个名字,这个文件夹里的东西只在unity 里能用,生成apk或ipa时是不会打包进去的,当然装在手机上也就不会运行。新建C#打包工具类,名字随便,放在Editor下。代码如下:
using UnityEngine;
using UnityEditor;
public class ExportAssetBundles: MonoBehaviour
{
[MenuItem("Custom/Build Asset Form Selection")]// 增加unity顶部菜单,点击该菜单运行下面的方法
static void ExportResourceRGB2()
{
// 打开保存面板,获得用户选择的路径
string path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "assetbundle");
if (path.Length != 0)
{
// 选择的要保存的对象
Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path, BuildAssetBundleOptions.CollectDependencies);
}
}
[MenuItem("Custom/Save Scene")]// 增加unity顶部菜单,点击该菜单运行下面的方法
static void ExportScene()
{
// 打开保存面板,获得用户选择的路径
string path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "unity3d");
if (path.Length != 0)
{
// 选择的要保存的对象
//Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
//打包
BuildPipeline.BuildPlayer(new string[1] { EditorApplication.currentScene }, path, BuildTarget.StandaloneWindows, BuildOptions.BuildAdditionalStreamedScenes);
}
}
}
代码中Object保存类型为 *.assetbundle
Scene保存类型为 *.unity3D。
核心代码BuildPipeline.BuildAssetBundle 与BuildPipeline.BuildPlayer,其中BuildTarget.StandaloneWindows为运行平台,如果是在安卓上运行要改为BuildTarget.Android
回到unity,新建StreamingAssets文件夹,选中Cube Prefab,选菜单栏Custom->Build Asset Form Selection 弹出保存选框,位置随意,这里保存在上面新建的StreamingAssets文件夹里(这个文件夹的作用->百度“Unity 特殊文件夹”),然后Custom->Save Scene,打包场景,同样随意位置保存。
完成示意图
2.加载
新建场景,编写load.cs,挂Camera上,运行
using UnityEngine;
using System.Collections;
public class Load: MonoBehaviour
{
//打包保存的位置
private string BundleURL = "file:///D:/UnityProject/ExportAssetBundles/Assets/StreamingAssets/Cube.assetbundle";
private string SceneURL = "file:///D:/UnityProject/ExportAssetBundles/Assets/StreamingAssets/Test.unity3D";
void Start()
{
Debug.Log(BundleURL);
Debug.Log(SceneURL);
StartCoroutine(DownloadAssetAndScene());
}
IEnumerator DownloadAssetAndScene()
{
using (WWW asset = new WWW(BundleURL))
{
yield return asset;
AssetBundle bundle = asset.assetBundle;
Instantiate(bundle.Load("Cube"));//打包的OBJ名
bundle.Unload(false);
yield return new WaitForSeconds(5);
}
using (WWW scene = new WWW(SceneURL))
{
yield return scene;
AssetBundle bundle = scene.assetBundle;
Application.LoadLevel("Test");//打包的Scene名
}
}
}
OK