How to play sounds effects in unity

Playing sound effects in Unity is very easy. Unity supports .aif, .wav .mp3 and .ogg.

To be able to play background music, create an empty GameObject, and add an Audio Source component. Drag the sound clip that you want to play in AudioClip and tick Play On Awake and Loop.

How do you turn off the background music? You can simply reference the GameObject where the Audio Source component is embedded and set to Inactive.

As for different playing sounds depending on the situation such as getting hit or firing lasers, add an AudioClip that can be edited from the Inspector and get a reference to the AudioSource component.

    [SerializeField]
private AudioClip _laserShot;
private AudioSource _audioSource;
// Start is called before the first frame update
void Start()
{
_audioSource = GetComponent<AudioSource>();
if (_audioSource == null) {
Debug.Log("Audio is null!");
}
}

When it’s time to Play the sound, assign the audio clip to the AudioSource component and play it.

    void FireLaser()
{
_audioSource.clip = _laserShot;
_audioSource.Play();
}

Then, on the Inspector, drag the audio clip that you would like to play for _laserShot.

That’s how it’s done.

I love game design and development.