Passing parameters between scences

For example I have 2 scenes named “Game” and “Ending”, and after the scene “Game” finished, I will load the scene “Ending” by

Application.LoadLevel("Ending");

But what if I have 2 endings for example inside “Ending”, I have something like

if (ending == 0) {
   LoadEnding1();
} else {
   LoadEnding2();
}

so that I want to pass the variable “ending” from scene “Game” to scene “Ending”?
Thanks

3 Answers

3

Just stumbled across this thread. I would recommend a class named ApplicationModel in which you insert a static variable named “ending” or something like that. Static variables stay even if you change scenes.

You can access the attribute like this: ApplicationModel.ending

Example class with static attribute:

public class ApplicationModel  
{
   static public int ending = 0;    // this is reachable from everywhere
}

Example usage:

if (ApplicationModel.ending == 1)
{
   LoadEnding1();

} else 
{
   LoadEnding2();
}

EDIT:
I published a blog post on this topic today covering both methods that where mentioned here. Including an example project for download.

You can check it out here: click me


this ^^^^^^^^^^^^^ is gold

A static variable can't be changed though. I suspect what he wants to do is change which ending is shown based on the actions of the player. In this case, static won't work.

I think you confused static with const, which indeed you cannot change. :)

The simplest way to do that, would be to have an empty object that contains that ‘ending’ variable, and use

DontDestroyOnLoad(endingObject);

before you load the next scene. Then, you can find (however you choose to do so) the ending object, and extract the variable from that!

Just like how @Ches81 pointed out you can use a static variable and access it every time. This is more secure.

Another way is by using PlayerPrefs. using PlayerPrefs, you can set values to variables and check those whenever you want. This is the easiest in my opinion, but might not be secure (unless you decide to use some kind of encryption techniques to encrypt the messages in playerprefs).

In your Game Script, use this when the level ends

PlayerPrefs.SetInt("Ending", 0);

In your Ending Script use this

int Ending = PlayerPrefs.GetInt(“Ending”);

if(Ending == 0){
      //do what you want
}

else{
      //alternate ending
}