Andre
Andre

Reputation: 39

Properly declare DontDestroyOnLoad

I am using DontDestroyOnLoad on a single gameObject. Everything works fine when I switch to other scenes. But problem appears when I come back to my initial scene where I had declared my DontDestroyOnLoad gameObject. It creates another instance of the gameObject which i do not need. I only need one instance of this running. What should I change?

public static Script instance;

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

Upvotes: 0

Views: 153

Answers (1)

Thomas
Thomas

Reputation: 1265

You're destroying your scipt instance, not the whole GameObject.

public static Script instance;

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

Upvotes: 4

Related Questions