# 【AssetBundle】
可以将游戏中需要加载的资源打包成一个文件,方便在运行时动态加载和卸载。
# 创建 AssetBundle
Editor/AssetBundleBuilder.cs
using UnityEditor;
using UnityEngine;
public class AssetBundleBuilder : Editor
{
[MenuItem("AssetBundles/Build AssetBundles")]
static void BuildAssetBundles()
{
// 设置打包输出路径和资源列表
AssetBundleBuild[] builds = new AssetBundleBuild[1];
builds[0].assetBundleName = "dajibundle";
builds[0].assetNames = new string[] { "Assets/DaJi/DaJiPrefeb.prefab"};
// 执行打包操作
BuildPipeline.BuildAssetBundles("DLC", builds, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows);
}
}
# 从资源服下载 AssetBundle
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
public class CommonSTSceneScript : MonoBehaviour
{
public string assetBundleURL = "https://vp666.cn/others/unity2022h5/DLC/dajibundle";
public string assetName = "Assets/DaJi/DaJiPrefeb.prefab";
void Start()
{
StartCoroutine(LoadAssetBundle());
}
IEnumerator LoadAssetBundle()
{
// 下载AssetBundle文件
UnityWebRequest www = UnityWebRequestAssetBundle.GetAssetBundle(assetBundleURL);
yield return www.SendWebRequest();
if (www.result == UnityWebRequest.Result.Success)
{
// 加载AssetBundle
AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(www);
if (bundle != null)
{
// 加载并实例化资源
GameObject asset = bundle.LoadAsset<GameObject>(assetName);
Instantiate(asset);
}
else
{
Debug.Log("Failed to load AssetBundle");
}
// 释放AssetBundle
bundle.Unload(false);
}
else
{
Debug.Log(www.error);
}
}
}
# 加载 AssetBundle
在代码中使用 AssetBundle.LoadFromFile 或 AssetBundle.LoadFromMemoryAsync 来加载 AssetBundle。例如:
AssetBundle myAssetBundle = AssetBundle.LoadFromFile("AssetBundles/myassetbundle");
# 卸载 AssetBundle
myAssetBundle.Unload(false);
# 加载资源
使用 AssetBundle 中的 LoadAsset 或 LoadAssetAsync 方法来加载需要的资源。例如:
GameObject myPrefab = myAssetBundle.LoadAsset<GameObject>("myprefab");
← 【全局局部坐标系转换】 【环绕观察台】 →