【Unity学习笔记】AssetBundle
发布人:shili8
发布时间:2025-03-05 05:17
阅读次数:0
**Unity学习笔记**
**AssetBundle**
在 Unity 中,AssetBundle 是一种特殊的资源包,它可以包含多个 Asset(例如3D 模型、纹理、音频等),并且可以在运行时动态加载。AssetBundle 的使用场景包括:
* **下载和更新内容**: 当游戏或应用程序需要下载新的内容(如新关卡、角色皮肤等)时,可以使用 AssetBundle 来实现。
* **减少内存占用**: 如果一个项目中有大量的资源,使用 AssetBundle 可以将这些资源分离到不同的包中,从而减少内存占用。
* **提高性能**: AssetBundle 的加载和卸载可以在后台进行,不会影响游戏或应用程序的主线程,从而提高性能。
**创建AssetBundle**
要创建一个 AssetBundle,需要使用 Unity 的 `BuildPipeline` API。下面是一个示例代码:
csharpusing UnityEngine;
using System.Collections.Generic;
public class CreateAssetBundle : MonoBehaviour{
void Start()
{
// 创建一个资源包 string assetBundleName = "MyAssetBundle";
AssetBundleCreateOptions options = AssetBundleCreateOptions.None;
AssetBundle bundle = BuildPipeline.BuildAssetBundle(options, null, assetBundleName);
// 将资源添加到包中 GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
Texture2D texture = new Texture2D(1,1);
texture.SetPixel(0,0, Color.red);
texture.Apply();
cube.GetComponent().material.mainTexture = texture;
AssetBundleCreateResult result = bundle.AddAsset(cube);
if (result != null)
{
Debug.LogError("Failed to add asset: " + result.error);
}
//保存资源包 string path = Path.Combine(Application.persistentDataPath, assetBundleName + ".assetbundle");
File.WriteAllBytes(path, bundle.ToArray());
// 关闭资源包 bundle.Close();
}
}
在这个示例中,我们首先创建一个资源包,然后将一个立方体 GameObject 添加到包中。最后,我们保存资源包到磁盘上。
**加载AssetBundle**
要加载一个 AssetBundle,需要使用 Unity 的 `AssetBundle` API。下面是一个示例代码:
csharpusing UnityEngine;
using System.Collections.Generic;
public class LoadAssetBundle : MonoBehaviour{
void Start()
{
// 加载资源包 string assetBundleName = "MyAssetBundle";
AssetBundle bundle = AssetBundle.LoadFromFile(Path.Combine(Application.persistentDataPath, assetBundleName + ".assetbundle"));
// 从包中加载资源 GameObject cube = bundle.LoadAsset("Cube");
Texture2D texture = bundle.LoadAsset("Texture");
// 使用加载的资源 cube.GetComponent().material.mainTexture = texture;
}
}
在这个示例中,我们首先加载一个资源包,然后从包中加载一个立方体 GameObject 和一个纹理 Texture。最后,我们使用这些资源来渲染一个立方体。
**AssetBundle 的优点和缺点**
* **优点**:
* 可以减少内存占用 * 可以提高性能 * 可以在运行时动态加载资源* **缺点**:
* 需要额外的代码来管理 AssetBundle * 需要额外的磁盘空间来保存 AssetBundle总之,AssetBundle 是 Unity 中一个非常有用的工具,可以帮助开发者减少内存占用、提高性能和实现动态加载资源。然而,它也需要额外的代码来管理和使用。

