How to Pass Data (And References) Between Scenes in Unity

How to pass data (and references) between scenes in Unity

Besides playerPrefs another dirty way is to preserve an object during level loading by calling DontDestroyOnLoad on it.

DontDestroyOnLoad (transform.gameObject);

Any script attached to the game object will survive and so will the variables in the script.
The DontDestroyOnLoad function is generally used to preserve an entire GameObject, including the components attached to it, and any child objects it has in the hierarchy.

You could create an empty GameObject, and place only the script containing the variables you want preserved on it.

Unity C# Passing Data Between Scenes

You can define a global variable for all scenes like this:

public static int didwhiteskin = 0;

So you can declare and initialise this variable in your first scene in the game, and then just refer it in any other scene you may create.

How do I carry over data between scenes in Unity?

There are a lot of ways to do this, but the simplest way to get something working quickly just until you get more familiar with Unity it to use a simple static class in your project that you can access from any script in any scene.

So if you were to make a new script in your project right now called SharedResources.cs and then pasted this into the script and saved it....

public static class SharedResources
{
public const int kSceneIs_TitleScene = 0;
public const int kSceneIs_ActualGameScene = 1;
public const int kSceneIs_HighScoreScene = 2;

public static int highScore = 0;
public static int enemyID = 0;

public static void sampleFunction()
{
//this is a sample method you can call from any other script
}

}

You could now be in a script in one scene and do this

SharedResources.highScore=SharedResources.highScore+20;
SharedResources.enemyID=5;

You could then open up a new scene and a script in that scene could access the high score

Debug.Log(SharedResources.highScore)
Debug.Log(SharedResources.enemyID)

You can also access constant and run subroutines that are in the static class as shown above.

The correct way to do this is up for debate and really depends on what your ultimate goal is. I will reference another link to a post that goes into more detail....

https://gamedev.stackexchange.com/questions/110958/unity-5-what-is-the-proper-way-to-handle-data-between-scenes

Ideally, you should read and understand the difference between using a simple static class versus one that derives from MonoBehavior, and also the different between a static class and a Singleton, which in many ways is much more powerful (but can also cause issues if you don't code it correctly)

Last but not least, don't forget you can also use the built in PlayerPrefs function in Unity to store scores and other settings that need to carry over between launches of the game....

https://answers.unity.com/questions/1325056/how-to-use-playerprefs-2.html



Related Topics



Leave a reply



Submit