Classes and Instances
The following is a code snippet for a Banana class:
Now clearly a single instance has no idea how many instances have been created, only the class can know this. So we need the notion of a class-level variable which is known as a Static in C# and Unity.
A static variable sets a variable on the mould rather than the instance. So in our fruity banana example the code would look like this. Notice how we use the "static" keyword to create a static variable.
So we can use this to keep track of which instances have already been created for our MusicManager. We do this by storing a static variable called "instance" which points to the current MusicManager instance. Then any future MusicManagers that get created will see that an instance already exists (because the "instance" variable is set) and so they will destroy themselves.
The code below shows this in action.