Unity How to have only one source audio?

Viewed 135

I have a source audio with this code:


public class Sound : MonoBehaviour {

    Static Sound instance;
    

    void Awake() 
    {
        if (instance != null)
        {
            Destroy(gameObject);
        }
        
        else
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }
    }


So when i change scenes the audio starts playing again. How do i limit it to having only 1?

Edit: How do i fix that? i get this error 1 - Unexpected symbol instance' in class, struct, or interface member declaration 2 - Unexpected symbol ;' in class, struct, or interface member declaration

1 Answers

Option 1:

The Singleton Pattern is likely to be your best choice when it comes to things like this. The intent of the Singleton Pattern is to restrict a class to only one Instance of itself. To read more about the pattern, see the Wiki on it.

It looks like you are already doing this (after your first edit) but the thing you're going to want to change is the capitalization of Static in your code. Static and static are two different things. For your sake, you are looking for static. This should fix your problem/error and allow you to use the Singleton Pattern correctly.

Option 2:

Also, another option if you want to avoid the typical Singleton Pattern would be to search through all GameObjects for any that have you Sound Class/Component on it. Then if there is already on in scene, have the GameObject that is trying to instantiate, destroy itself. You can do this with the following code:

public class Sound : MonoBehaviour 
{
    void Awake() 
    {
        int numSoundInstances = FindObjectsOfType<Sound>().Length;
        if (numSoundInstances > 1)
        {
            Destroy(this.gameObject);
        }
    
        else
        {
            DontDestroyOnLoad(this.gameObject);
        }
    }
}

In my opinion, this is way less efficient then using the Singleton Pattern. This is because using FindObjectsOfType forces the code to check every GameObject that is currently in the game. Depending on the amount of GameObjects in the game, this can be very taxing on the system.

Related