Question about the singleton

Hello its me again with my annoying questions :smiley:

So i understand the logic behind the singleton
void Awake()
{
SetUpSingleton();
}
private void SetUpSingleton()
{
if (FindObjectsOfType(GetType()).Length > 1)
{
Destroy(gameObject);
}
else
{
DontDestroyOnLoad(gameObject);
}
}

So step by step

  1. (FindObjectsOfType(GetType()).Length > 1) we want to see how many scripts we can find type .
    Lets say we are on scene 0 at the moment and we have 1 MusicPlayer type.
    Now when we want to load scene 1 how can the program count 2 MusiPlayer type?
    in my logic we are on scene 0 with 1 MusicPlayer type if we load Scene 1 then Scene 0 is deleted.
    The only logical way is for me is that Unity is Loading scene 1 and after is loaded then deletes scene 0 so
    the SetUpSingleton(); can run?
    Sorry if i give you headache Nina

Hi Shaktillar,

The job of our “singleton” is to keep our MusicPlayer game object “alive” if we load another scene. While it is true that scene 0 gets destroyed when we load a new scene, our MusicPlayer will continue to exist in the new scene.

When we load scene 1 and there is another MusicPlayer in that scene, we would have two MusicPlayer objects for a brief moment. The Awake() and the Start() method of our persistent MusicPlayer will not get called again. Only Awake() and Start() of the new MusicPlayer object will get called. And that’s the reason why our “singleton” does not destroy our “first” MusicPlayer but the new ones only.

Did this make sense? :slight_smile:


See also:

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

Privacy & Terms