我正在显示一个库存场景,我是通过LoadScene Additive实现的。 我将播放器转移到这个新场景。
这也很好。在加载新场景之前,我要存储对当前活动场景的引用,如下所示:
private Scene PrevScene;
PrevScene = SceneManager.GetActiveScene();
现在,当玩家通过按下键退出库存场景时,我想我可以像这样简单地将先前的场景再次设置为活动场景:
SceneManager.MoveGameObjectToScene(UIRootObject, PrevScene); //transfer the player to the new scene
SceneManager.SetActiveScene(PrevScene);
但是,未加载前一个场景。相反,库存场景变得越来越亮,所以我想一次又一次地加载库存场景。
我的方法有根本上的错误吗?还是需要更多代码才能查看我在做什么?
如果是,我在下面说明了整个代码:
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 bool _bInventoryShown = false;
private Scene PrevScene;
void Update()
{
if (Input.GetKeyDown(KeyCode.I))
{
Debug.Log("Is inventory currently shown: " + _bInventoryShown);
//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.MoveGameObjectToScene(UIRootObject, PrevScene); //transfer the player to the new scene
SceneManager.SetActiveScene(PrevScene);
}
_bInventoryShown = !_bInventoryShown;
}
}
IEnumerator loadScene(string SceneName)
{
AsyncOperation nScene = SceneManager.LoadSceneAsync(SceneName, LoadSceneMode.Additive);
nScene.allowSceneActivation = false;
while (nScene.progress < 0.9f)
{
Debug.Log("Loading scene " + " [][] Progress: " + nScene.progress);
yield return null;
}
//Activate the Scene
nScene.allowSceneActivation = true;
while (!nScene.isDone)
{
// wait until it is really finished
yield return null;
}
Scene nThisScene = SceneManager.GetSceneByName(SceneName);
if (nThisScene.IsValid())
{
Debug.Log("Scene is Valid");
SceneManager.MoveGameObjectToScene(UIRootObject, nThisScene); //transfer the player to the new scene
SceneManager.SetActiveScene(nThisScene); //activate the scene
}
else
{
Debug.Log("Invalid scene!!");
}
}
}
答案 0 :(得分:0)
知道了:我需要调用SceneManager.Unload(SceneName)。