Sanity Check - Static MusicPlayer instance understanding

Understanding:
Static MusicPlayer instance is effectively a global variable for the class. It only exists once and exists in the class and all child objects of the class. Any object of the class can change it and this is reflected throughout all the class objects.

Therefore it can only be in one state at a time.

Question:
It’s behaving like a boolean, only it isn’t declared a boolean. It is ‘null’ or ‘this’.
This is confusing witchcraft.

1 Like

Hi @laurakh

Static MusicPlayer instance is effectively a global variable for the class. It only exists once and exists in the class

Effectively yes

and all child objects of the class

Need to be a little careful with the terminology here, by “child objects of the class” I assume you are referring to other members of the class, e.g. member variables, methods etc, if so then yes.

If when you say “child objects of the class” you refer to instances of the class, e.g. when a new copy of the class is created, then also yes.

If you are referring to “child objects” from the perspective of GameObjects within Unity, then possibly not.

Any object of the class can change it and this is reflected throughout all the class objects.

Any instance of the class, yes, correct.

Therefore it can only be in one state at a time.

Correct, which can be very useful, but also exposes it to accidental changes if we are not careful.

Question:
It’s behaving like a boolean, only it isn’t declared a boolean. It is ‘null’ or ‘this’.
This is confusing witchcraft.

I would argue that that is more of a statement than a question :wink:

It is indeed behaving in that manner, it is effectively nothing or something, and in the case of something will only be an instance of itself.

You could also achieve the same outcome using a boolean variable, one advantage of this approach is that you can just access the thing itself, rather than having to do another check to see what it evaluates to first, before accessing the thing.

You will often see this approach in C# when there is a use of properties and a private constructor. Instead of being able to directly create a new instance of the object, you would access it directly through the property, which in turn, then checks for and creates if necessary a new instance of itself in the static variable.

Slightly different approach in Block Breaker as you do not really instantiate this yourself, as it is attached to a GameObject and Unity is performing this for you.

Hope this helps with the sanity :slight_smile:

1 Like

Privacy & Terms