Passing variables from Scene to Scene?

I want to pass a variable from one scene to the next.
I did it with PlayerPrefs, is that the only way to do it?

Is there a way to declare global variables that are accessible by all scripts at run time?

The Unity Manual says statics are available across all instances of a class(?)
What does that mean?

If I learned it correctly, when adding “static” to the variable declaration; for example:

public static int P1score;

This attaches the variable and its value to the class and not to an instance of the class. I think that is the definition of global variable. Hopefully it’s what you’re looking for.
@ben and Brice talked about the concept in a neat video somewhere during the Laser Defender section involving Legos that I can’t seem to find, so I’m unable to share a link.

The typical way for runtime data is to use a Singleton as described in Lessons 64-66 (Block Breaker). Scoring is a classic example.

If you want it to be persisted between game sessions, PlayerPrefs is one way to go (e.g. High Score).

You can use statics for runtime data, but it introduces complexities with thread safety and static references and it can be hard to debug if it’s not working as expected.

Thank you, I revisited those lectures and Singletons are the best way to go, but I’d like to learn more about statics. I looked them up on unity manual but there is refers to objects in a scene that do not move.

Statics are a programming concept rather than a Unity specific one - have a look on the C# MSDN, StackOverflow etc.

Just adding to @ninjachimp’s reply…

A couple of useful pages from Microsoft (the second link has more detail);

It can be done with a singleton object that is not destroyed on scene change (like with the music player in blockbuster). I did that with my version: https://github.com/tdvance/Buster specifically in this class: https://github.com/tdvance/Buster/blob/master/Assets/Scripts/MainGame.cs .

Privacy & Terms