第一次研究AssetBundles。本次讲如何用AssetBundles打包一个资源。又如何加载到场景里。
从最基础的入手:
首先将下列脚本放到Asset里,什么都不用管,放进去就OK
注意: 代码中 BuildPipeline.BuildAssetBundle这个方法在高版本中被废弃了,我用的是5.3.2f1版本还可以用,5.4就不能了。
- using UnityEngine;
- using System.Collections;
-
- 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);
-
- }
-
- }
-
- }
当上面代码放入项目里时会看到在菜单里有一个Export的东西出现,里面有两项:第一个是选择打包文件,第二个是打包所有文件。
此文用来讲解选择一个东西打包(一般来说要被打包的东西都是预设prefab)。然后我们新建一个cube在场景里,把他做成预设物体命名为89。
因为window的本地加载都是在StreamingAssets文件里加载的(其他平台不一样),所以我们在Asset下手动新建一个StreamingAssets文件夹。
如下图:

来看一下我们的cube现在的位置:(目的是用来对比一会加载进来的位置,其实位置是不会改变的)

之后就在project里选择89然后进行打包,选择路径(路径很重要,加载时要用,看下图)会弹出这个窗口,然后为89命名为666,之后会被保存在StreaningAssets文件夹里。(下图中由于搜狗输入法截图时输入中文有问题所以只能写英文了)

打包之后刷新一下unity会在打包的文件里看到刚打包的东西:

至此,我们的打包功能已经完成。
..............................................接下来讲解如何加载。..........................
以下方法是windows电脑加载的方法(安卓和iOS与PC互相都不一样):
把下列脚本随便绑定到一个物体上就OK(该代码是用来加载物体了)
- 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:///"+ "C:/Users/Desktop/new/New Unity Project/Assets/" + "/StreamingAssets/666.unity3d");
-
-
- yield return www;
-
-
- Instantiate(www.assetBundle.mainAsset);
-
-
- }
-
-
- }
注:要更换文件路径只能更换"C:/Users/Desktop/new/New Unity Project/Assets/",在window里本地加载必须在StreamingAssets文件里。
之后我们运行unity看到在场景里加载进了一个cube而且位置和之前是一样的。

本文许多代码并无优化也不严谨,目的是为了让刚接触AssetBundles的小伙伴能够更清晰的看到打包实现过程和加载过程。也就是说老司机请绕行!呵呵哒!
|