Pass data and references between scenes in Unity

Hello programmers, In this article, I will show how to “Pass data and references between scenes in Unity”

As a beginner at Unity, everyone faces the problem of passing data between the scenes which can bring a huge difference in the game. Let’s get started with the building process.

Create a New C# Script

  • Open the Main scene.
  • In the Project window, go to Assets > Scripts.
  • Create a new script and name it as GameManager.
  • In the Hierarchy, create a new empty GameObject and name it GameManager.
  • Assign your new script to the GameObject.

C# Script

  • Open the GameManager script in your chosen IDE.
  • Delete the default Start() and Update() methods, then add the following code to create a static member to the GameManager class:

 

public class GameManager : MonoBehaviour
{
    public static GameManager Instance;

    private void Awake()
    {
        Instance = this;
        DontDestroyOnLoad(gameObject);
    }
}
This code allows you to access the GameManager object from any other script.

Modify Awake()

It is called when the script instance is being loaded.

The first line of code stores “this” in the class member Instance — the current instance of GameManager. You can now call GameManager.Instance from any other script.

Update the Awake method with the following code:

private void Awake()
{
    if (Instance != null)
    {
        Destroy(gameObject);
        return;
    }

    Instance = this;
    DontDestroyOnLoad(gameObject);
}
  • Save all the changes
  • Return and try testing in the Unity Editor.

Also read: How to create a custom Skybox in Unity3D

Leave a Reply

Your email address will not be published.