I only have Instance.this

I’m referencing variables between different codes using instances such as Player.instance.health;.
What’s the difference between only having

private void Awake()
    {
       instance = this;
    }

as opposed to

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

The first will overwrite the value of instance every time Awake is run. This is useful if you want to create a static reference to a script but you don’t plan to have the script float. By definition, this is not a singleton.

The second is a singleton pattern. It checks if Instance has a value, and if not, it assigns the script to it and sets the gameobject to not be destroyed (thus is floats between scenes). If it has a value, then it destroys the new copy. You have to do this to avoid having multiple copies of a script that you only want one of. Like a GameManager script or AccountManager.

1 Like

Some super-simple Singleton examples to take and modify:

Simple Unity3D Singleton (no predefined data):

Unity3D Singleton with Prefab used for predefined data:

These are pure-code solutions, do not put anything into any scene, just access it via .Instance!

1 Like

Thank you. Now I understand how the Singleton works.

So, just to reference code Player.instance.health; between two scripts this should be sufficient, right?

private void Awake()
    {
       instance = this;
    }

Yes indeed, as long as you keep in mind order of initialization. All Awakes will be called before all Starts, assuming all objects are in scene and enabled.

Beware that you may hear chuff from computer-science-y people about how the above is an anti-pattern. Fortunately such patterns exist to help us who actually make and ship games deliver them in a timely fashion. :slight_smile:

Here is some timing diagram help:

2 Likes

Thank you all for the answers.