我遇到一个奇怪的问题:
我添加了一个场景,它确实显示了,但是Unity告诉我:
ArgumentException: SceneManager.SetActiveScene failed; scene 'inventory' is
not loaded and therefore cannot be set active
UnityEngine.SceneManagement.SceneManager.SetActiveScene (Scene scene)
PlayerScript.enableScene (System.String SceneName) (at
Assets/PlayerScript.cs:83)
PlayerScript.OnFinishedLoadingAllScene ()
我不确定这种情况如何发生。 有人在我的代码中看到错误吗?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
//First, load scene with SceneManager.LoadSceneAsync.Set allowSceneActivation to false so that the scene won't activate automatically after loading.
public class PlayerScript : MonoBehaviour
{
public GameObject UIRootObject;
private AsyncOperation _SceneAsync;
private bool _bInventoryShown = false;
private Scene PrevScene;
void Update()
{
if (Input.GetKeyDown(KeyCode.I))
{
//player pressed I to show the inventory
if (!_bInventoryShown)
{
//store the currently active scene
PrevScene = SceneManager.GetActiveScene();
//start loading the inventory scene
StartCoroutine(loadScene("inventory"));
}
else
{
//player pressed I again to hide the inventory scene
//so just set the previous scene as the active scene
SceneManager.SetActiveScene(PrevScene);
}
_bInventoryShown = !_bInventoryShown;
}
}
IEnumerator loadScene(string SceneName)
{
AsyncOperation nScene = SceneManager.LoadSceneAsync(SceneName, LoadSceneMode.Additive);
nScene.allowSceneActivation = false;
_SceneAsync = nScene;
//Wait until we are done loading the scene
while (nScene.progress < 0.9f)
{
Debug.Log("Loading scene " + " [][] Progress: " + nScene.progress);
yield return null;
}
//Activate the Scene
_SceneAsync.allowSceneActivation = true;
Scene nThisScene = SceneManager.GetSceneByName(SceneName);
if (nThisScene.IsValid())
{
Debug.Log("Scene is Valid");
SceneManager.MoveGameObjectToScene(UIRootObject, nThisScene);
SceneManager.SetActiveScene(nThisScene);
}
else
{
Debug.Log("Invalid scene!!");
}
}
}
我也尝试了以下方法:
AsyncOperation nScene = SceneManager.LoadSceneAsync(SceneName, LoadSceneMode.Additive);
nScene.allowSceneActivation = false;
//Wait until we are done loading the scene
while (!nScene.isDone)
{
Debug.Log("Loading scene " + " [][] Progress: " + nScene.progress);
yield return null;
}
Debug.Log("Scene was loaded!");
从不调用最后一个日志(“场景已加载”)。
答案 0 :(得分:1)
来自AsyncOperation.progress(另请参见示例)
返回操作进度。 (只读)返回操作完成的接近程度。当进度浮点达到1.0并调用isDone时,操作完成。如果将allowSceneActivation设置为false,则进度将停止在0.9,直到将其设置为true。这对于创建加载条非常有用。
您应该已经设置了一段时间,但是无论如何都不要再等待
// ...
while (nScene.progress < 0.9f)
{
Debug.Log("Loading scene " + " [][] Progress: " + nScene.progress);
yield return null;
}
//Activate the Scene
_SceneAsync.allowSceneActivation = true;
while (!nScene.isDone)
{
// wait until it is really finished
yield return null;
}
//...