[solved] Using Boolean instead of "instance = this;"

Just finished the lecture 65 about the static/instance music player and I tried writing my own code before watching the solution.

My solution was:

static bool MusicPlaying = false;

void Start () {
	
	if (MusicPlaying == true) {
		GameObject.Destroy(gameObject);
	}
	
	else {
		MusicPlaying = true;
	}
	
	GameObject.DontDestroyOnLoad(gameObject);

}

But the video used a different method, using something like:

static MusicPlayer instance = null;
void Start() {
    if(MusicPlayer != null) 
    { Destroy(gameObject); }
    else 
    { instance = this;}
}

They both seem to work, but is my method somehow wrong or inefficient? I am not a programmer so I don’t really know whether I’m committing some big error that I don’t know yet, or just an alternate but equally alright solution.

What you’ve done there is introduce brittleness. The static bool kind of serves the same purpose as having a static instance of MusicPlayer, but it’s not really the Singleton pattern (i.e. guaranteed to only be one MusicPlayer). If some other code set MusicPlaying to false after the MusicPlayer was instantiated, you’d get multiple instances. It’s a global flag, not a Singleton, and it’s easy to break.

It was a good creative attempt at the problem, but the provided solution is much more robust.

Also, FYI, rather than

if (MusicPlaying == true)

you can just use

if (MusicPlaying)

as MusicPlaying, as a bool, already evaluates to either true or false.

2 Likes

Oh thanks, that’s a very understandable answer. And also thanks for the shortcut.

well said, I had the same question

Thanks for the answer. I did a similar thing using a static int count of the number of instances of music player. Obviously suffers from the same brittleness issues.

So some other code can’t deallocate the instance and set it to null ?

Privacy & Terms