3D AUDIO
Add a Gunshot Sound Effect to Pistol’s Activation Event
To configure the necessary logic to have a gunshot sound effect play when the player pulls the trigger (activates the pistol interactable), we need to use the Audio Source Component.
WHAT IS THE AUDIO SOURCE COMPONENT?
The Audio Source in Unity is like a virtual speaker that plays a custom sound clip/music within the game. The Audio Source Component determines how the sound is heard to the player, whether it sounds like it is coming from all directions constantly (2D Sound) or from one spot with the sound being dropped off within a configured distance (3D sound).
AUDIO SOURCE COMPONENT
The audio source component includes several properties we will use to customize the way our gunshot sound effect works within the project.
PROPERTIES
- Audio Clip — Reference to the sound clip file needed to be played
- Play on Awake — If enabled, the sound will start playing the moment the scene is launched. If disabled, audio clip will only play when using the Play() command from a script.
- Spatial Blend — Sets how much the audio clip is treated as 3D/2D.
→ 1 = audio source is 3D which means the audio clip is affected by spatial position and spread
→ 0 = audio source is 2D which means all spatial attenuation (the loss of energy of a signal) is ignored
CONFIGURE GUNSHOT SOUND
To have a gunshot sound effect play when the player activates the pistol interactable, we need to accomplish the following steps…
STEP 1 — ATTACH AUDIO SOURCE COMPONENT
Within the Pistol GameObject, we need to attach the Audio Source Component
STEP 2 — CONFIGURE AUDIO SOURCE COMPONENT
To configure the audio source component to act and sound the way way we want, we need to…
- Reference the wanted Audio Clip
- Disable Play on Awake
- Have the Audio Clip be 3D
STEP 3 — PLAY SOUND WITHIN ACTIVATE EVENT
Within the XR GRAB INTERACTABLE SCRIPT on the Revolver GameObject we need to subscribe the Play() function within the Audio Source Component to the Activate Interactable Event
CONCLUSION
Now when the player pulls the trigger or activates the pistol game object, the sound clip will play.