Dev Day 44: Trigger an Audio Clip in Unity3D

Objective: Trigger an audio clip when the laser is fired in Unity3D.

Step 1: In Unity, select the Player GameObject in the Hierarchy window, add an Audio Source component, and uncheck the Play On Awake option.

Step 2: in the Player script, create a private variable of type AudioClip named _laserSFXClip and add [SerializeField].

Go back into Unity, select the Player GameObject in the Hierarchy window, and drag an audio clip into the Laser SFX Clip slot in the Player (Script) component in the Inspector window.

Step 3: In the Player script, create a private variable of type AudioSource and name it _audioSource.

In the Start() method, use GetComponent to access the Audio Source component and have that equal to the _audioSource variable. Null check the _audioSource variable and if it is not equal to null, then assign the _laserSFXClip variable to the AudioClip slot within the Audio Source.

Step 4: In the InstantiateLaser() method, within the Input.GetKeyDown if statement, after the Laser Prefab has been instantiated, play the _laserSFXClip using _audioSource.Play().

Save the script, go back to Unity, play the scene, and when the space key is pressed the Laser will instantiate and trigger the Laser SFX clip.

Unity Developer