Unity AssetBundle引用计数 打包和加载 代码示例
时间: 2023-11-03 11:21:40 浏览: 141
以下是一个简单的 Unity AssetBundle 引用计数、打包和加载的代码示例:
打包资源文件:
```csharp
using UnityEditor;
using UnityEngine;
public class AssetBundleBuilder : MonoBehaviour
{
[MenuItem("Assets/Build AssetBundle")]
static void BuildAssetBundle()
{
string assetBundleDirectory = "Assets/AssetBundles";
// 创建目录
if (!Directory.Exists(assetBundleDirectory))
{
Directory.CreateDirectory(assetBundleDirectory);
}
// 打包
BuildPipeline.BuildAssetBundles(assetBundleDirectory, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows64);
}
}
```
加载 AssetBundle 文件和资源文件:
```csharp
using System.Collections;
using UnityEngine;
public class AssetBundleLoader : MonoBehaviour
{
AssetBundle assetBundle;
string assetBundlePath = "Assets/AssetBundles/myassetbundle";
IEnumerator Start()
{
// 加载 AssetBundle 文件
UnityWebRequest request = UnityWebRequest.GetAssetBundle(assetBundlePath);
yield return request.SendWebRequest();
assetBundle = DownloadHandlerAssetBundle.GetContent(request);
// 加载资源文件
GameObject prefab = assetBundle.LoadAsset<GameObject>("myPrefab");
// 使用资源文件
Instantiate(prefab);
// 释放 AssetBundle 中的资源
assetBundle.Unload(false);
}
}
```
在使用 AssetBundle 的过程中,需要注意避免重复加载同一个 AssetBundle,以及及时释放不再使用的 AssetBundle 资源,避免内存泄漏。
阅读全文