How to use a static global variable in Unity C# across different scenes?

Windows 10 version 21H2 (OS Build 19044.1889)
Unity 2021.3.8f1
Google Cardboard XR Plugin for Unity version 1.16.0
XR Plugin Management Version 4.2.0 - October 21, 2021
Android 8, 10, 12
iOS 12.5.5

Hi,

I wondered is there any other options to use static global variable in C# across different scenes loaded ?

For example, PlayerPrefs saved data can be retrieved from different scenes when loaded ( using SceneManager.LoadScene API ), but to prevent from accessing storage file which slowing down speed, I want to put the data globally in memory for accessing during runtime.

Any idea ?

You can use a singleton

public class GlobalData : MonoBehaviour
{
    public static GlobalData Instance { get; private set; }

    // Put your data in here
    public int MyData { get; set; }

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

// Usage:
GlobalData.Instance.MyData = 123;

but singletons are to be used sparingly

1 Like

ic, that’s the usage of singleton. Thanks again :smiley:

Privacy & Terms