【发布时间】:2018-11-30 20:14:39
【问题描述】:
我正在展示一个库存场景,我通过 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!!");
}
}
}
【问题讨论】:
标签: unity3d