Playing sound effects in Unity

Samarth Dhroov
2 min readMay 26, 2021

--

The exercise here demonstrates 3 ways in 2D settings to trigger sound clips.

Here is the most basic way to enable a sound clip.

  • Attach an audio source on the object that observes collision interactions and add the audio clip that you’d like to play if a successful collision happens.
  • For this, you’d need to deploy a handle to the Audiosource and then use the play( ) method.
private AudioSource _laserAudio;
C#
  • As simple as it looks, the sound shall play every time the spacebar key is pressed.

The second way is to attach the sound clip directly to a prefab of explosion. Here, the explosion has to be a standalone game object and hence could play the sound on its own.

Unity

The third way is where we can use a method named “PlayClipAt( )”. This facilitates the destruction of a game object but not the sound.

  • Declare a serialized field of AudioClip type.
  • Select the objects that are holding that script and you should see a container wherein you have to drag the audio clip of interest.
Unity
C#
  • As you can see, even though the destroy method comes in right after the audio trigger, the sound would not stop playing because the method sort of catches the sound and plays it at the transform position of the game object just before it got destroyed.

Thank you very much

--

--

No responses yet