AssetBundle
AssetBundle
1.打包
将要打包的资源在inspector中的预览窗口下设置要打包在AssetBundles下的路径和后缀名(可任意取)。新建一个C#脚本,脚本内容如下:
using System.IO; using UnityEditor; public class CreateAssetBundles { [MenuItem("Assets/Build AssetBundles")]//生成菜单目录 static void BuildAllAssetBundles() { string assetBundleDirectory = "Assets/AssetBundles";//指定AssetBundles文件夹的目录 if (!Directory.Exists(assetBundleDirectory)) { Directory.CreateDirectory(assetBundleDirectory);//如果没有,则创建文件夹 } BuildPipeline.BuildAssetBundles(assetBundleDirectory, BuildAssetBundleOptions.None,BuildTarget.StandaloneWindows); } }
2.读取
场景中物体上挂载一个脚本,脚本代码如下:
using UnityEngine; public class LoadAssetBundle : MonoBehaviour { void Start() { AssetBundle bundle = AssetBundle.LoadFromFile("Assets/AssetBundles/this/wall.ab");//找到AB包 GameObject cubeWall = bundle.LoadAsset<GameObject>("CubeWall");//找到AB包中的物体 Instantiate(cubeWall);//实例化物体 } }
运行后即可实例化物体。