HOME/Articles/

Easy Way to Play Sound in Unity

Article Outline

AudioManager

When dealing with AudioClip in Unity, one thing you don't want to do is manage the AudioSource every time you play. Therefore, we recommend using the following AudioManager class. Even if you want to perform more complex controls such as stopping the sound once played, changing the volume, etc., you should customize this AudioManager class.

using UnityEngine;

public class AudioManager : MonoBehaviour
{
    private static AudioManager Instance;

    private AudioSource AudioSource;

    private void Awake()
    {
        if (Instance != null)
        {
            Destroy(gameObject);
            return;
        }
        Instance = this;

        DontDestroyOnLoad(gameObject);
        AudioSource = gameObject.AddComponent<AudioSource>();
    }

    public static AudioManager GetInstance()
    {
        if (Instance == null)
        {
            var obj = new GameObject(nameof(AudioManager));
            obj.AddComponent<AudioManager>();
            Instantiate(obj);
        }

        return Instance;
    }

    public void PlayOneShot(AudioClip clip, float volume = 1f)
    {
        AudioSource.PlayOneShot(clip, volume);
    }

    public void PlayBGM(AudioClip clip, float volume = 1f)
    {
        AudioSource.Stop();

        AudioSource.clip = clip;
        AudioSource.loop = true;
        AudioSource.volume = volume;
        AudioSource.Play();
    }
}

AudioManager

Usage

The AudioManager class instance can be accessed from anywhere, so it is very easy to use. There is only one thing to do, just pass the AudioClip to the PlayOneShot method or the PlayBGM method.

public class AudioTest : MonoBehaviour
{
    [SerializeField]
    private AudioClip TestClip;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Alpha0))
            AudioManager.GetInstance().PlayOneShot(TestClip);
    }
}

Samples

See the source code here, unity-audio-manager.