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!

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

select() vs selectExpr() in Spark

Another view for filtering function

The Anatomy of a Feature Flag

CSS Basic: Pseudo classes

Granting IAM permissions to pods in EKS using OIDC

Crodo VS Pulse Pad: Battle Of Launchpads

A quick guide to help you picking up the best side project to work next

Learning dotNet Core — CI/CD

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adam Reed

Adam Reed

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!

More from Medium

2D Light Flicker in Unity

Height Maps and Pixel Displacement (Game Dev Day 80)

Adding a burst laser powerup

Ledge Grab System: Part IV