ohtrobinson
ohtrobinson

Reputation: 13

How do you pass a variable to another script and/or scene in Unity?

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

Answers (3)

Prateek Jain
Prateek Jain

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

RSez
RSez

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:

  • Put a "loader" game object on each of your scenes, which will instantiate the GameManager if it's not
  • GameManager maintains a static reference to itself, so you can access it everywhere (after the awake method) by calling GameManager.instance.myScore (to be sure that loader has the time to instantiate it).

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

C-JARP
C-JARP

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

Related Questions