Unity Audio: How to Play Sound Effects in Unity

Adding sounds to Unity requires little code, just create a variable for the sound source and play it in a method based on some event or condition.

The easiest way to play audio is to attach it to some object when it appears. Simply add an “Audio Source” component to that object, set “Audio Clip”, and select the option “Play on Awake”. When the object is initialized, the audio will play.

To play audio on some event or when some condition is met, we need to write a script. As in the above case, we use the “Audio Source” component and set Audio Clip, but the “Play when awake” option should be unchecked. Then in the script attached to the object, we create the variable “Audio Source”, assign it to the “Audio Source” component and in the method where we call some action, we play the audio effect using the “Play” method: “AudioSource.Play();”.

In case our object should make a sound after we collect it, we need another method to make it work. Every object disappears after we collect it, so when we attach a sound to an object, it will not play after it is destroyed. To play the sound after collecting some item, we can use the “PlayClipAtPoint()” method of the “Audio Source” class. We also need an additional variable “AudioClip” where we will store our sound effect.

For different scenarios, we should know different methods to play sound effects.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store