我希望能够在我的Unity项目中加载整个场景。
我已经创建了同时包含三个场景(scene01,scene02,scene03)的资源包。
资源包导出如下:
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
public class CreateAssetBundle : EditorWindow {
public const string bundlePath = "AssetBundle.unity3D";
[MenuItem("Bundle/Create")]
static void Open()
{
var w = EditorWindow.GetWindow <CreateAssetBundle>("Create bundle");
w.MyInit();
w.Show();
}
private Dictionary<string, bool> ScenesSelection;
void MyInit()
{
Debug.Log("Init window");
this.ScenesSelection = new Dictionary<string, bool>();
foreach (var scene in EditorBuildSettings.scenes)
{
Debug.Log("Add scene : " + scene.path);
this.ScenesSelection.Add(scene.path, false);
}
}
void OnGUI()
{
if (this.ScenesSelection == null)
{
this.MyInit();
}
foreach (var scene in EditorBuildSettings.scenes)
{
if (this.ScenesSelection.ContainsKey(scene.path))
{
this.ScenesSelection[scene.path] = EditorGUILayout.Toggle(scene.path, this.ScenesSelection[scene.path]);
}
}
if (GUILayout.Button("Create bundle"))
{
List<string> selectedScenes = new List<string>();
foreach (var scene in EditorBuildSettings.scenes)
{
if (this.ScenesSelection[scene.path])
{
selectedScenes.Add(scene.path);
}
}
BuildPipeline.PushAssetDependencies();
BuildPipeline.BuildPlayer(selectedScenes.ToArray(), bundlePath, BuildTarget.iPhone,
BuildOptions.UncompressedAssetBundle | BuildOptions.BuildAdditionalStreamedScenes
);
BuildPipeline.PopAssetDependencies();
}
}
然后我将我的程序包上传到服务器上。 接下来,我创建了一个脚本来加载程序包,如下所示。
using UnityEngine;
using System.Collections;
public class LoadBundleScene : MonoBehaviour {
public string bundlePath = "AssetBundle.unity3D";
public string url;
IEnumerator Start ()
{
var download = WWW.LoadFromCacheOrDownload (url, 1);
yield return download;
// Handle error
if (download.error != null)
{
Debug.LogError(download.error);
return true;
}
var bundle = download.assetBundle;
Debug.LogWarning(bundle.Contains("scene01"));
Application.LoadLevelAdditive ("scene01");
}
}
我的最后一个调试返回值是“false”。Unity提示:“场景' scene01 '(-1)无法加载,因为它尚未添加到构建设置中。”我做错了什么?我需要在iOS和Android设备上使用它。有什么想法吗?
foreach (var scene in EditorBuildSettings.scenes)
是问题所在。你需要按照我最初的建议,在构建资源包时将场景包含在构建设置中。运行时,请务必检查控制台是否显示:“Add scene : YOUR SCENE NAME”。 - Gary Riches