2015-11-09 74 views
1

我在Unity3D中用C#为移动设备制作游戏,但无法弄清楚如何检查当前场景之前加载的场景。我需要检查这个来改变玩家gameobject的重生点。首先,我添加了一个简单的脚本来我的按钮(loadnextscene和loadprevscene)检查之前加载的场景

public class SwitchScene : MonoBehaviour { 
    public int sceneNumber; 

    public void LoadScene(int sceneNumber) { 
     Application.LoadLevel(sceneNumber); 
    } 
} 

第二个脚本从用户处理触摸输入和改变玩家物体的移动。例如:如果玩家点击第二关卡中的“加载上一个场景”按钮以再次切换到第一关卡,我想将玩家对象的重生点设置在第二关卡上的右半部分上屏幕,而不是像第一次开始游戏时那样在左侧。

我试过用Singleton和PlayerPrefs,但没有成功。

+0

您之前的尝试出了什么问题?如果您与我们分享,我们可能会发现错误并帮助您解决问题。 – Serlite

回答

2

您需要将场景编号保存到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); 
    } 
} 

最后,在你的场景开始()检查Indestructable.instance.prevScene并相应地做你的魔法。

此处了解详情: http://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html

*我没编译代码,所以可能会有一些错误,但这是一般的想法。

+1

这似乎是最可行的答案。我会建议一个静态的int变量或字符串在一个Singleton类中保持这个并永不销毁。这是类似的:) – ApolloSoftware

+0

我不明白currentScene变量应该有哪些值以及在哪里使用它。当我在加载下一个场景之前将sceneNumber存储在prevScene中时,它仅将当前场景索引作为prevScene的值返回给我。 –

+0

对不起,我没有说清楚:要知道你当前的场景是什么,你可以使用'Application.loadedLevel'。所以这是当前场景,您只需在加载之前将该值分配给prevScene。我更新了这个例子。 –