Unity之資源打包之AssetBundle
1.打包資源
using UnityEngine;
using System.Collections;
using UnityEditor;
public class AssetsBundle
{
/// <summary>
/// 打包資源
/// </summary>
public void BundleAssets()
{
//創建資源包數組,裏面只能存一個資源包
AssetBundleBuild[] assetBundleBuild = new AssetBundleBuild[1];
//資源包命名
assetBundleBuild[0].assetBundleName = "cube.assetbundle";
//資源路徑
assetBundleBuild[0].assetNames = new string[] { "Assets/Resources/Cube.prefab" };
//打包
BuildPipeline.BuildAssetBundles(Application.persistentDataPath, assetBundleBuild,BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows);
}
}
2.創建菜單
using UnityEditor;
class OperateMenu
{
[MenuItem("Tools/BundleAssets")]
public static void Bundle()
{
AssetsBundle assetsBundle = new AssetsBundle();
assetsBundle.BundleAssets();
}
}
3.加載打包資源
using System.IO;
using UnityEngine;
/// <summary>
/// 加載打包資源
/// </summary>
class LoadBundleAssets : MonoBehaviour
{
private void Start()
{
byte[] buffer = GetBuffer();
//從流中加載出資源包
AssetBundle assetBundle = AssetBundle.LoadFromMemory(buffer);
GameObject cube = assetBundle.LoadAsset<GameObject>("Cube");
Instantiate(cube, Vector3.zero, cube.transform.rotation);
}
/// <summary>
/// 獲取打包資源
/// </summary>
/// <returns></returns>
private byte[] GetBuffer()
{
//讀取資源包文件,並寫入字符流
FileStream fs = new FileStream(Application.persistentDataPath + "/cube.assetbundle",FileMode.Open);
byte[] buffer = null;
buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
return buffer;
}
}