unity3d - SceneManager 没有激活我之前的场景
问题描述
我正在展示一个库存场景,我通过 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!!");
}
}
}
解决方案
明白了:我需要调用 SceneManager.Unload(SceneName)。
推荐阅读
- python - 使用特定条件Python加入列表中的项目
- javascript - datalist 如何判断下拉菜单中是否选择了输入
- wordpress - 如何使用“withSelect”更新动态 Gutenberg 块中的 REST-API 调用
- javascript - 从 Google 工作表中读取行但返回的数组为空
- c# - 如何在 xamarin.forms 中获取应用程序本身的目录
- java - 调用另一个类的 JUnit 测试
- oop - 如何通过python中的方法从类中删除实例?
- intellij-idea - 如何在 Intellij 中使用“在路径中查找”选项?
- bash - sqlite dot 命令变量扩展,如 bash
- discord.js - 如何在 discord.js 中为我的不和谐音乐机器人添加均衡器?