Global Variables or passing data between levels

I am just starting out with Unity and I feel like I am getting pretty far, fairly quickly. There is one thing that I do not seem to be grasping: How or where do you store information that should remain persistent? If you Application.LoadLevel(0), and then the player loses a life and accumulates a score of 1000, how do you inform level 1 of the data that was previously held in level 0 when you call Application.LoadLevel(1)?

Is there some sort of repository for information at the Application level that I am not seeing?

Take a look at PlayerPrefs on scripting documentation.

http://unity3d.com/support/documentation/ScriptReference/PlayerPrefs.html

1 Like

Take a scene such as a splashscreen or menu that loads near the start of the game, set DontDestroyOnLoad() so that it never unloads, and attach your globals to a empty game object in that scene.

6 Likes

Thanks Rbn_3D. PlayerPrefs is a great solution and was very easy to implement.

Hoff, I am also interested in the DontDestroyOnLoad() method, because this is more along the lines of what I was initially thinking. What happens to the GameObject when you call it? Or more appropriately, where is it? Is it added to the hierarchy of all loaded levels, or only the currently running one? What if I use LoadLevelAdditive()?

If you’re just keeping track of values, you can use static variables in your script. So, for example, if in a script GameState you declare

static var score = 0;

(in javascript)

GameStats.score could be accessed from any other script, in any scene and the value will persist between scenes.

5 Likes

Thanks Dougxing !

That is exactly what I was looking for Dougxing. Thanks.

Very helpful Dougxing. Thanks!

Thanks! Herlped me out alot. :smile:

You can create an object in first scene, attach a sript to it and sen value of variable in this script. For example if you want to send user login script attachet to game object that will survife after second scene load should be:

Set userLogin in first scene and read in second.

Complete example can be found in my blog http://unity-tutorials.blogspot.com/. Listing 20 and 21.

1 Like

Great Help !!

have both scripts in the same Directoy (Not sure if this is nessesary depends on the IDE & Project linkage of files)
set your shared variables as Static Public
use

ScriptName.VariableName = for assignment from another script.

PLAYERPREFS, SERIOUSLY???

6 Likes

Thanks, I used this to stop my background music from starting all over again when loading next level of my game.

Here a full tutorial on how to handle data between scenes: https://gamedevelopertips.com/how-to-handle-data-between-scenes-in-unity/

You will find a few examples and best practices. I hope is useful!