UnityCommunity / UnitySingleton

The best way to implement singleton pattern in Unity.
https://en.wikipedia.org/wiki/Singleton_pattern
MIT License
458 stars 61 forks source link

Awake DestroyObject with condition? #1

Closed lexnewgate closed 6 years ago

lexnewgate commented 6 years ago
  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.

hasanbayatme commented 6 years ago

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

Thanks.

lexnewgate commented 6 years ago

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.

hasanbayatme commented 6 years ago

Ah, no problem, that's my pleasure.