unity 是怎么加载assetbundle

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了unity 是怎么加载assetbundle相关的知识,希望对你有一定的参考价值。

Unity会下载Assetbundle本地中,它的工作原理是先通过(版本号和下载地址)先在本地去找看有没有这个Assetbundle,如果有直接返回对象,如果没有的话,在根据这个下载地址重新从服务器或者本地下载。这里版本号起到了很重要的作用,举个例子,同一下载地址版本号为1的时候已经下载到本地,此时将版本号的参数改成2那么它又会重新下载,如果还保持版本号为1那么它会从本地读取,因为本地已经有版本号为1的这个Assetbundle了。你不用担心你的资源本地下载过多,也不用自己手动删除他们,这一切的一切Unity会帮我们自动完成,它会自动删除掉下载后最不常用的Assetbundle,如果下次需要使用的话只要提供下载地址和版本后它会重新下载。  我们在聊聊Assetbundle中的脚本,在移动平台下Assetbundle里面放的脚本是不会被执行的,还记得我们打包前给两个Prefab挂上了脚本吗?在手机上将Assetbundle下载到本地后,加载进游戏中Prefab会自动在本地找它身上挂着的脚本,他是根据脚本的名来寻找,如果本地有这条脚本的话,Prefab会把这个脚本重新绑定在自身,并且会把打包前的参数传递进来。如果本地没有,身上挂的条脚本永远都不会被执行。  在Prefab打包前,我在编辑器上给脚本中的变量name赋了不同值,当Prefab重新载入游戏的时候,它身上脚本的参数也会重新输出。  如果你的Assetbundle中的Prefab上引用的对象,那么这样做就会出错了,你需要设定他们的依赖关系。或者运行时通过脚本动态的载入对象。 参考技术A 直接参考如下源码:
using UnityEngine;
using System.Collections;

public class ReanAssetbundle : MonoBehaviour

//不同平台下StreamingAssets的路径是不同的,这里需要注意一下。
public static readonly string m_PathURL =
#if UNITY_ANDROID
"jar:file://" + Application.dataPath + "!/assets/";
#elif UNITY_IPHONE
Application.dataPath + "/Raw/";
#elif UNITY_STANDALONE_WIN || UNITY_EDITOR
"file://" + Application.dataPath + "/AssetBundleLearn/StreamingAssets/";
#else
string.Empty;
#endif

void OnGUI()
if(GUILayout.Button("加载分开打包的Assetbundle"))
StartCoroutine(LoadGameObjectPackedByThemselves(m_PathURL + "One.assetbundle"));
StartCoroutine(LoadGameObjectPackedByThemselves(m_PathURL + "Two.assetbundle"));
StartCoroutine(LoadGameObjectPackedByThemselves(m_PathURL + "Three.assetbundle"));



if(GUILayout.Button("加载打包在一起的Assetbundle"))
StartCoroutine(LoadGameObjectPackedTogether(m_PathURL + "Together.assetbundle"));



//单独读取资源
private IEnumerator LoadGameObjectPackedByThemselves(string path)
WWW bundle = new WWW (path);
yield return bundle;

//加载
yield return Instantiate (bundle.assetBundle.mainAsset);
bundle.assetBundle.Unload (false);


IEnumerator LoadGameObjectPackedTogether (string path)

WWW bundle = new WWW (path);
yield return bundle;

Object one = bundle.assetBundle.Load ("One");
Object two = bundle.assetBundle.Load ("Two");
Object three = bundle.assetBundle.Load ("Three");

//加载
yield return Instantiate (one);
yield return Instantiate (two);
yield return Instantiate (three);
bundle.assetBundle.Unload (false);

以上是关于unity 是怎么加载assetbundle的主要内容,如果未能解决你的问题,请参考以下文章

unity5本地文件assetbundle怎么加载

unity怎么通过lua加载一个游戏对象

unity 发布webgl怎么加载assetbundle

unity 是怎么加载assetbundle

Unity 移动端怎么加载网络上的视频??

怎么在另一个程序加载或者调用UNITY3D