Singleton question

I don’t totally understand why we’re using a singleton in this context.

From what I can see, the ‘music player’ (on which our audio source sits) is instantiated once, and only once, each time the scene restarts.

I understand that the music restarts when the player dies (which we’re wanting to avoid) - however, the ‘music player’ doesn’t appear to duplicate on each scene restart.

To put it another way: for a singleton pattern to be necessary, I’d have expected to see an additional ‘music player’ appearing in the heirarchy each time the scene restarted - so after 3 x scene restarts, we’d have 3 x music players, etc. (But this isn’t the case.)

So, why the need for the singleton pattern?

Many thanks :slight_smile:

I would say it is exactly for preventing the music player from being recreated when the scene restarts.

Let me give some more details:

When the player dies, the scene is reloaded and everything on it is recreated. This is fine, but the music stops playing because the music player is recreated when the scene loads. We want to avoid this, so we set the music player game object to DontDestroyOnLoad. Now, when the scene reloads, the music player will not be destroyed, but the scene will create a new one. Now we have 2. The new music player runs Awake() and finds that there is already a music player in the scene, so it destroys itself. This is why you don’t see 3 music players after 3 restarts.

That’s it. Now the music will continue to play, and we will only ever have one music player in the scene

2 Likes

Thanks so much for the clear explanation: that’s really helpful and makes total sense :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms