UnityCommunity/UnitySingleton

Awake DestroyObject with condition?

lexnewgate opened this issue · 3 comments

  protected virtual void Awake()
    {
        if (instance == null)
        {
            instance = this as T;
            DontDestroyOnLoad(gameObject);
        }
        else if (instance != this)
        {
            //If there is already an instance of this class, destroy the object we just created.
            Debug.LogWarning("Attempted to spawn more then one singleton object. destroying new instance of " + gameObject.ToString() + "\nIf you would like more than one instance, ensure that the class you have written does not Inherit from a Singleton class.");
            Destroy(gameObject);
        }
    }

I found another snippet from Naphier which the instance!=this make sense when destroy it.

Could you please explain it why you didn't add condition? Thanks.

Hi.
That's the same, which condition do you mean?
As I see, both scripts work the same way.

Thanks.

Sorry for wasting your time as a unity novice. I thought awake will be invoked when the gameobject is enabled. I didn't realize it will be only invoked once during its lifetime.

Ah, no problem, that's my pleasure.