How To Play Sound Effects Through Code In Unity

Say you are making a game and you wanted to play a sound effect when you fired a gun. You can do this in a few different ways.

One way is to add an “Audio Source” component to your game object and call the sound effect through a script. In the example below, I’ve attached the “Audio Source” component and the following code to my player character object. by dragging and dropping my gunshot sound effect into the Audio Source component I can now trigger the sound effect each time I press the Spacebar key.

You can also trigger audio effects through your script without an “Audio Source” component too. Just make sure you drag and drop the desired sound effect into the “_audioClip” reference in the inspector, and use the script example below in the script you are wanting to call it from.

Hi, my name is Adam Reed and I am a software engineer specializing in Unity and C# development. Feel free to scroll through and check out some of my work!