c# - 检查之前加载的场景

标签 c# unity-game-engine scene

我正在 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/

相关文章:

c# - 如何在 WCF REST 服务中有可选参数?

c# - JSON post 在 IE 中有效,在 FF 中无效

c# - .NET 字典中的重复键?

c# - 错误 : Unable to find Mono. 确保 Mono 的 '/bin' 文件夹已添加到环境的 PATH 变量(在 MacOS 上)

ios - Swift ios7 Storyboard - 自己启动主场景

c# - 动态替换 MVC 4 中的标签

c# - Unity - 如何为每个好 Action 显示几秒钟的文本

iphone - 我的手机和 iPad 在 Unity3d 中使用什么屏幕尺寸

javafx - 在同一场景中加载新的 fxml

java - 舞台中额外的顶部空间是否包含在场景的大小中?