我正在 Unity3D 中使用 C# 为移动设备制作游戏,但不知道如何检查当前场景之前加载的场景。我需要检查此项以更改玩家游戏对象的生成点。首先,我向按钮添加了一个简单的脚本(loadnextscene 和 loadprevscene)
public class SwitchScene : MonoBehaviour {
public int sceneNumber;
public void LoadScene(int sceneNumber) {
Application.LoadLevel(sceneNumber);
}
}
第二个脚本处理用户的触摸输入并更改玩家对象的移动。
所以,举个例子:如果玩家在第二个关卡中点击“加载上一个场景”按钮再次切换到第一个关卡,我想将玩家对象的生成点设置在屏幕的右半部分而不是像第一次开始游戏时那样在左侧。
我尝试使用 Singleton 和 PlayerPrefs,但没有成功。
最佳答案
您需要在LoadScene之前将场景编号保存到某个变量中,然后在场景加载后检查它。
唯一的问题是这个变量将在新场景加载后被销毁。因此,为了防止这种情况,您可以使用 DontDestroyOnLoad
。这是你要做的:
首先,创建一个新的空游戏对象,并将以下脚本附加到它:
using UnityEngine;
using System.Collections;
public class Indestructable : MonoBehaviour {
public static Indestructable instance = null;
// For sake of example, assume -1 indicates first scene
public int prevScene = -1;
void Awake() {
// If we don't have an instance set - set it now
if(!instance )
instance = this;
// Otherwise, its a double, we dont need it - destroy
else {
Destroy(this.gameObject) ;
return;
}
DontDestroyOnLoad(this.gameObject) ;
}
}
现在,在加载之前,将场景编号保存在 Indestructable 对象中:
public class SwitchScene : MonoBehaviour {
public int sceneNumber;
public void LoadScene(int sceneNumber) {
Indestructable.instance.prevScene = Application.loadedLevel;
Application.LoadLevel(sceneNumber);
}
}
最后,在场景 Start() 中检查 Indestructable.instance.prevScene
并相应地发挥你的魔力。
更多信息请点击这里: http://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html
*我没有编译代码,所以可能会有一些错误,但这是总体思路。
关于c# - 检查之前加载的场景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33615804/