How to Use Sound Effects in Unity
I will be showing two different ways to play sound in Unity. The first is without using code and the other is through code.
How to Play Sound Without using code
- Add an Audio Source to one of the game objects in the hierarchy
- The next thing you want to do is add the audio clip into the AudioClip slot
- Now the audio will play when you start the game if you have Play On Awake Selected.
- This way is good for things like ambient noise or background music.
How to Play Sound Using Code
- This way will start similar to the previous way. Select a game object and add an Audio Source. Make sure to uncheck play on awake.
- Open the player script and add a reference to the audio source and the audio clip.
- In the start function you will set the Audio Source using get component. Make sure to null check since you are using get component.
- Now go to where you want to call the sound effect. For this example I am calling a laser sound when the laser is shot. You will set the Audio Source as the Audio clip and then play the Audio Source.
- In Unity make sure to set the audio clip in the inspector.
- Now the Audio should play when the conditions you set are met.
This way is good for playing sound effects that need to play at specific times. Things like gunshots or grenade explosions.