So, I did this by keeping a count of the number of instances made, and limiting it (in this case) to 1. However, I like this method more because it’s easier to use it later if I wanted to have a maximum number of instances of an object. Is there another benefit to keeping one instance as a static variable as shown in this video?
I rattled my brain around the challenge part and came out with this, and it works just as fine…
public static int musicPlayerCount = 0;
void Start ()
{
musicPlayerCount++;
int x = MusicPlayer.musicPlayerCount;
GameObject.DontDestroyOnLoad(gameObject);
if (musicPlayerCount >= 2)
{
GameObject.Destroy(gameObject);
print("duplicate MusicPlayer died");
}
}
I did something sort of the same. I used a Static bool value and on start if it was true it would destroy the object, else set the value to true:
public static bool player = false;
void Start () {
if (!player) {
GameObject.Destroy(gameObject);
print("Duplicate Music Destroyed");
} else {
player = true;
}
}//end Start