I was attempting the challenge to only make one Music Player, and I came up with creating a static integer called “count” and setting it to 0 (then incrementing it each time) rather than creating a static MusicPlayer object. Question: What are the pros and cons of doing this with an integer rather than a MusicPlayer object?
public class MusicPlayer : MonoBehaviour {
static int count = 0;
void Start () {
if (count > 0) {
Destroy(gameObject);
print ("Killed duplicate music player");
} else {
count++;
GameObject.DontDestroyOnLoad(gameObject);
}
}
}
Two rather small advantages of using MusicPlayer instance:
You can always get reference to “one and only” true MusicPlayer object. You can use FindObjectOfType as well, of course. But the instance is faster and “nicer”.
A counter in code should be used when we can really count something. In this case you could have a boolean as well: because you actually use just values 0 and 1, never more than 1.
An integer has a maximum value - whilst it is highly unlikely you would ever reach it, it is possible that by incrementing the counter like this to check effectively an on/off state you could try to exceed the maximum value - at which point your game will crash.
If you really like Block Breaker and want to test the theory… you just need to play 2,147,483,647 times… on the next turn, it’ll crash
Of course, you could just set your counter to be 2147483647 and play once… but where’s the fun in that right?
I initially used the “.instance” field but have decided the code is cleaner if I just used “FindObjectOfType”, while only instantiating a singleton from an _init scene that does nothing but instantiate singletons and go to the next scene. Other methods kept getting race conditions for me.
The downside is more work is needed to run a scene other than _init that uses the singletons.