When you return to the menu you will have duplicate objects.
Both objects have this code on them:
if (FindObjectsOfType(GetType()).Length > 2)
{
Destroy(gameObject);
}
What I believe might be happening is that both objects are determining that there are more than one of them and both objects are deleting themselves.
Instead, you might want to take a different approach to making sure only one exists. Here is some code I wrote for a music player that might help:
public GameObject musicPlayer;
void Awake() {
//When the scene loads it checks if there is an object called "MUSIC".
musicPlayer = GameObject.Find("MUSIC");
if(musicPlayer==null)
{
//If this object does not exist then it does the following:
//1. Sets the object this script is attached to as the music player
musicPlayer = this.gameObject;
//2. Renames THIS object to "MUSIC" for next time
musicPlayer.name = "MUSIC";
//3. Tells THIS object not to die when changing scenes.
DontDestroyOnLoad(musicPlayer);
}else{
//If there WAS an object in the scene called "MUSIC" (because we have come back to
//the scene where the music was started) then it just tells this object to
//destroy itself
Destroy(this.gameObject);
}
}
↧