Home > Blockchain >  How do I stop gameobject from creating a copy
How do I stop gameobject from creating a copy

Time:08-24

so in the main menu of my game I have an empty game object with an audio source that plays the music and also has DontDestroyOnLoad, now that works well when you change scene into the actual game, but the player has the option to go back to the main menu, if that happens the main menu scene creates the same gameObject with the same AudioSource, but now there are two sources of music playing over eachother, and it can stack as long as the player goes into the game and the menu, any way I can get around this? Thanks in advance!

CodePudding user response:

For what you're trying to do, you want to go with the Singleton pattern. Here's an example

public class YourAudioPlayer : MonoBehaviour
{
    public static YourAudioPlayer Instance; // Stores your single instance of this object

    private void Awake()
    {
        // If an instance of this class has already been created, destroy this new instance
        if (Instance != null)
        {
            Debug.Log("Duplicate Music player destroyed");
            Destroy(gameObject);
        }

        Instance = this; //This will only execute the very first time this class is instantiated, thanks to the above if statement
    }
}

CodePudding user response:

I dont recommend using DontDestroyOnload or Singleton to achieve what you want.

Simpyle use Scenes to manage your game like a Root scene that never deletes. You can use more than one scene actively.

To manage your things like Audio, Settings etc, create services.

  • Related