0
votes

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);
    }
1

1 Answers

4
votes

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);
}