Reputation: 13
I am working on a game that requires a score. I would like to pass my variable to another scene in c#. I've tried lots of solutions but none of them have worked! I have a public static variable as my score and I would like to pass it to a lose screen.
Upvotes: 0
Views: 3743
Reputation: 587
You can make an Empty GameObject and Use DontDestroyOnLoad() at the Empty GameObject and store any data u want to pass to another scene in the script attached to the EmptyGameObject and retrieve data from the EmptyGameObject in next Scene.
Refer following video on youtube to see this concept in action:
https://www.youtube.com/watch?v=VauchY1uIB4
Upvotes: 0
Reputation: 271
PlayerPrefs is a very bad habit to store data between scenes. It has been designed to store data between game executions, not scenes ; because it will persist your data locally on your computer.
In the case where you want to pass data between scenes, it could be a good idea to make a GameManager, as explained in one tutorial on the official website.
The idea is:
Just take a look at the tutorial, it's very well explained. But do not use PlayerPrefs to pass data through your scenes.
Upvotes: 6
Reputation: 1088
I would suggest you use playerprefs: http://docs.unity3d.com/ScriptReference/PlayerPrefs.html
example, in a scene you set the variable: PlayerPrefs.SetInt("Score",value);
in another scene you get it PlayerPrefs.GetInt("Score",0);
The 0 on the second call is the default value, if it does not exist, it will return you 0
Upvotes: 0