Making a static int instead of a static MusicPlayer object

Hi there

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);
		}
	}
}

Thanks

Antony

Two rather small advantages of using MusicPlayer instance:

  1. 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”.
  2. 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.

Other than that I do not see any big difference.

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 :slight_smile:

Of course, you could just set your counter to be 2147483647 and play once… but where’s the fun in that right? :slight_smile:

1 Like

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.

1 Like

Thank you all for your comments, and have a fab New Year!

Antony

1 Like

I did the same thing when presented with the challenge. My code looked like this.

public static int NumberOfPlayers = 0;
void Start () {

if (NumberOfPlayers < 1) {
		GameObject.DontDestroyOnLoad (gameObject);
		NumberOfPlayers++;
	} else
		GameObject.Destroy (gameObject);

}

In my opinion, you took the correct approach. But, if you use a bool instead, it’s even simpler:

public class MusicPlayer : MonoBehaviour {
	static bool shouldDestroy;
	void Start () {
		if (shouldDestroy) {
			Destroy(gameObject);
			print ("Killed duplicate music player");
		} else {
			GameObject.DontDestroyOnLoad(gameObject);
			shouldDestroy = true;
		}
	}
}

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.