不能用
//伪代码
asssetbundle.LoadAsset()
代码讲的是,加载了一个包含*.unity的资源包,然后加载资源包中的BG 1纹理,这个BG 1纹理是存在的。结果纹理加载失败了~
会抛出异常:InvalidOperationException: This method cannot be used on a streamed scene AssetBundle.表示LoadXX方法不能应用在动态场景资源包上。
- 起因
任何一个包含*.unity的资源包都属于动态场景资源包,对应assetBundle.isStreamedSceneAssetBundle = true,动态场景资源包是不允许手动去访问其内部的资源的。
- 重点
- 如果你的资源需要通过代码访问,那么在打包时不要与*.unity文件捆绑为一个文件
但我们又需要.unity,如何办?
/// <summary>
/// 拓展思考:一个舍近求远的操作,怎么就不用AssetBundle.Load()??
/// </summary>
/// <param name="relativePath"></param>
/// <param name="sceneName"></param>
/// <param name="mode"></param>
/// <param name="onComplete"></param>
/// <returns></returns>
static IEnumerator CorLoadLevel(string relativePath,string sceneName,LoadSceneMode mode,Action onComplete) {
//string path = "file://" + Application.dataPath + "/Resources/" + sceneAssetBundle;
string path = "file://" + Application.persistentDataPath + "/AssetBundle/Android/" + relativePath;
sceneName = Path.GetFileNameWithoutExtension(sceneName);
WWW www = WWW.LoadFromCacheOrDownload(path, 0);
yield return www;
if (www.error == null)
{
//下面一行的对象ab貌似没用到,但是不写的话,会报错如下:
//Scene 'sceneAssetBundleTest'(-1) couldn't be loaded because it has not been added to the build settings or the AssetBundle has not been loaded.
//To add a scene to the build settings use the menu File->Build Settings...
//UnityEngine.SceneManagement.SceneManager:LoadSceneAsync(String)
//场景没加到Build Settings的场景列表中或AssetBundle未加载。
AssetBundle ab = www.assetBundle; //将场景通过AssetBundle方式加载到内存中
//Application.LoadLevelAsync(sceneName); 弃用的
AsyncOperation asy = SceneManager.LoadSceneAsync(sceneName,mode); //sceneName不能加后缀,只是场景名称
onComplete();
yield return asy;
}
else
{
Debug.LogError(www.error);
onComplete();
}
}
调用方法
//GameRoot请自行找一个monobehaviour,或者GameFacade替代
GameRoot.Instance.StartCoroutine(CorLoadLevel(assetPath, assetName, mode, onComplete));