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;
}
}