Trouble with deleting duplicate MusicManager

I’m trying to create an object that plays background music and will persist throughout multiple scenes. Unfortunately, when I loop back to the scene that initially had the object inside, I now have two of the same object.

I’ve tried to remedy this issue by tracking down and deleting all instances of that object while creating a new object with the same properties as the original. However, when I do this in my script, it gets hit with a “StackOverflowException.”

Here’s the part of the script I’m having trouble with:

    if (GameObject.FindGameObjectsWithTag("MusicManager") == null)
    {
        Instantiate(musicController, Vector3.zero, Quaternion.identity);
        DontDestroyOnLoad(this.gameObject);
    }

    if (GameObject.FindGameObjectsWithTag("MusicManager").Length > 1)
    {
        Destroy(gameObject);
    }

1 Answer

1

The best way of doing this is making the musik manager a singleton. Code in C#

public class MusicManager : MonoBehaviour{
    private static MusicManager instance = null;

    void Start(){
        if(instance == null){
            instance = this;
            DontDestroyOnLoad(this.gameObject);
        } else {
            Destroy(this.gameObject);
        }
    }
}

This will make sure, that there is never more than one instance of the MusicManager in your scene ever.