1

I have some codes below

 [SerializeField] int playerLives = 3; void Awake() { int numGameSessions = FindObjectsOfType<GameSession>().Length; if(numGameSessions > 1) { Destroy(gameObject); } else { DontDestroyOnLoad(gameObject); } } 

Explain situation:

  • First I have one obj in my hierarchy like this enter image description here and then the Don't Destroy On Load appears, and the game works normally.
  • But when I put 3 Game Session into my Scene, all disappear and the Don't Destroy On Load doesn't appear, why does this happen?
1
  • Is there any hmm like conflict between the 3 Game Session obj ? cuz Awake will be called at the same time and on all the obj ? Commented Aug 9, 2022 at 11:12

1 Answer 1

2

In your example, when you have 3 items when the first Awake starts all the 3 Game Sessions are already attached to the scene, so it will destroy all GameSession objects. This is not the right way to do Singleton pattern in Unity. A better approach would be:

using UnityEngine; public class Singleton : MonoBehaviour { private static Singleton instance; public Singleton Instance { get { return instance; } } void Awake() { if (instance == null) { instance = this; DontDestroyOnLoad(this.gameObject); } else { Destroy(this); } } } 

you can then get your instance by calling Singleton.Instance

Sign up to request clarification or add additional context in comments.

1 Comment

I will try to explain the flow and you guys check it right or wrong ok ? the private static Singleton instance; means that you declare an empty shell that contains our instance, then a property to get it. In the Awake function, if your shell hasn't had an instance yet, then give it the object to which this script is attached, then don't destroy it when another scene is loaded. Otherwise, just destroy this obj. But which will be this if awake is called at the same time for any obj ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.