Hi Andrew,
I’ve taken a look, it was a bit easier to see in context etc.
Running the game if I go from the Splash scene to Level 1, the Hierarchy only displays one MusicPlayer, the second one which is found, in the Level 1 scene is destroyed.
Now, if we look at what we are outputting to the console, we state how many objects of type MusicPlayer existing, and on Level 1 that is two (briefly), we destroy the second one and then get a new count and output that to the console, it still says two.
What hadn’t occurred to me earlier (when I suggested adding the extra debug statement) is that you make the call to destroy the second music player and output the new count in the same frame, but, and this is the important part, the GameObject isn’t destroyed until the end of that frame. So where we added the code to get the new count and output the value, at that point in time there still are two.
For the end of that frame, its unlikely that you’d notice any ill effects of it existing so very briefly, however, what you can do to work around this issue (the issue is only caused because of the way the singleton is being attempted), you can add this line;
gameObject.SetActive(false);
before the Destroy(gameObject);
statement.
Not being active it will not be able to do anything, any Find
methods will also not return it, if you run the game again now you’ll note that the console outputs that the number of MusicPlayer’s after action is now one.
Note, you have Collapse turned on in the console, so turn it off and you’ll see those messages appear in the order you’d expect them.
Hope this helps explain what is/was going on. Moving forward you could leave the statement in to deactivate the GameObject and just remove all of the Debug.Log
statements, and that second Find
statement, so you’d end up with this;
private void Awake()
{
int numMusicPlayers = FindObjectsOfType<MusicPlayer>().Length;
if (numMusicPlayers > 1)
{
gameObject.SetActive(false);
Destroy(gameObject);
}
else
{
DontDestroyOnLoad(gameObject);
}
}
Hope this helps