This question already has an answer here:
- Unity - pass data between scenes 2 answers
I am creating a simple number guessing game in unity3d.
I want to open a new scene on button click and change the text of a text element present in the loaded scene from the current scene.
I have been able to open new scene on button click but how can i access the text element in other scene so that i can change its text from the current scene.
This is what i have so far but it obviously throws NullReferenceException
because i can't access the text element in another scene from current scene.
SceneManager.LoadScene("End Scene");
gameResultText.text = "You Won!!"; //<-------this line throws the exception
gameResultText.color = Color.green;
Better solution I came up with:
Make a script that sets a static string variable. This script must be in your Game scene and will hold the result.
Put this script on your result text in the end scene. This script will retrieve the result and display it.
This way, it will set the text as soon as the new scene is loaded.
Previous/alternative method:
If you already have the scene open, one option would be to add a script to the "You won!" text which holds a static variable with a reference to itself.
So like this.
Then you can call the reference to that GameObject from anywhere in the other scripts, including between scenes.
Like this
ResultTextScript.Instance
Note though that you cannot call the reference in the Awake method, as that is where the variable is initialized, you can use it after the Awake methods have been called though.
Basically
gameObject go = ResultTextScript.Instance.gameObject
I do not believe there is a way to modify the context or objects of a scene that is not currently open.
In your function where you are loading the scene, right before you call load scene you can access that text like so:
GameResults.finalText = "You Win!";
orGameResults.finalText = "You Lose!";
load your scene, and on your text object give it a script like this:
There are other things you can use as well is, storing the game results in
PlayerPrefs
and loading the string or int you stored inPlayerPrefs
preferences at the start of your end scene. This will help you avoid creating an unnecessary class or static variable.So Like before you can do:
PlayerPrefs.SetString("GameResults", "You Win!");
orPlayerPrefs.SetString("GameResults", "You Lose!");
load your scene, and on your text object give it a script like this: