1.首先我们把这段代码拷贝下来,放进工程,不要托给任何物体,就放在那不要理它。
using UnityEngine; using UnityEditor; public class ExportAssetBundles { [MenuItem("Export/Build AssetBundle From Selection - Track dependencies")] static void ExportResource () { // Bring up save panel string path = EditorUtility.SaveFilePanel ("Save Resource", "", "New Resource", "unity3d"); if (path.Length != 0) { // Build the resource file from the active selection. Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets); BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path, BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets); Selection.objects = selection; } } [MenuItem("Export/Build AssetBundle From Selection - No dependency tracking")] static void ExportResourceNoTrack () { // Bring up save panel string path = EditorUtility.SaveFilePanel ("Save Resource", "", "New Resource", "unity3d"); if (path.Length != 0) { // Build the resource file from the active selection. BuildPipeline.BuildAssetBundle(Selection.activeObject, Selection.objects, path); } } }我们仔细看一下,其实打包的.unity3d格式的文件也类似assenbundle,只不过是换了个不同的后缀名而已。
当我们创建完,保存好后我,我们会发现菜单的导航栏多了这2项
2.我们在选中我们需要打包的预设物体(也即是Prefab)。然后选中上面的第一项进行打包成.unity3d格式的文件。如图
3.设置名字,路径等(路径很重要,待会加载会用到。)如图:
4.刷新下。你就会看见这个了:
这个就是我们打包后动态加载的内容。
5. 现在我来说下怎么动态加载它吧,直接上代码
using UnityEngine; using System.Collections; using System.IO; public class LoadUnity3d : MonoBehaviour { // Use this for initialization void Start() { StartCoroutine(LoadScene()); } // Update is called once per frame void Update() { } IEnumerator LoadScene() { //文件路径,也就是我们打包的那个 WWW www = new WWW("file:///" + Application.dataPath + "/Bundles/My Prefab.unity3d"); yield return www; Instantiate(www.assetBundle.mainAsset); } }
6.我们再新建一个空物体,讲我们这个脚本托给他,运行,你就能看见我们的预设也加载出来了。
效果如下: