a, 制作1个胶囊体预制体
b, 设置预制体CapsuleAB为AB包
1, 进入CapsuleAB的"Inspector"面板
2, 设置AssetBundle如下所示
①, ab/good , ab为文件夹 good为生成AB文件的名称
②, 后面的ab 可以理解为good文件的格式. 如下图所示:
1, 核心代码:
using System.IO; using UnityEditor; using UnityEngine; public class CreateAssetBundles : MonoBehaviour { [MenuItem("AlexHu/Build AssetBundles")] static void BuildAllAssetBundles() { string assetBundleDirectory = "AssetBundles"; if(!Directory.Exists(assetBundleDirectory)) { Directory.CreateDirectory(assetBundleDirectory); } BuildPipeline.BuildAssetBundles(assetBundleDirectory, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows); } }
注解:
①, assetBundleDirectory : 将生成的AB资源放在项目更目录下(并非Assets目录下) , 如上面的ab/good , 就是在assetBundleDirectory 下生成一个ab文件夹, 将good放在ab文件夹中
②, 要将 CreateAssetBundles 放在Assets/Editor文件夹下.
③, 这样 Unity IDE上会出现AlexHu的菜单, 操作 AlexHu -> Build AssetBundles 就可以生成AB包了
代码如下:
using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; /// <summary> /// 简单的AB,从本地加载 /// </summary> public class ABSimpleDemo : MonoBehaviour { private void Start() { AssetBundle ab = AssetBundle.LoadFromFile("AssetBundles/ab/good.ab"); GameObject go = ab.LoadAsset<GameObject>("CapsuleAB"); GameObject prefab = Instantiate(go); prefab.transform.parent = this.transform; } }
scene: