- Home /
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
Answer by Ches81 · Jan 24, 2013 at 02:36 PM
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
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. :)
Answer by syclamoth · Mar 20, 2012 at 07:05 AM
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!
Answer by tubelightboy · Jun 16, 2021 at 08:42 PM
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
}
Your answer

Follow this Question
Related Questions
Passing a Script Name to a Function 2 Answers
Blend tree like effect on one animation ? 0 Answers
How to pass Predicate to a Coroutine? 1 Answer
RPC , string parameter is sent, but length is 0 1 Answer
Instanciate with parameter 2 Answers