Unity Audio: How to Play Sound Effects in Unity

Adding sounds to Unity requires little code, just create a variable for the sound source and play it in a method based on some event or condition.

The easiest way to play audio is to attach it to some object when it appears. Simply add an “Audio Source” component to that object, set “Audio Clip”, and select the option “Play on Awake”. When the object is initialized, the audio will play.

To play audio on some event or when some condition is met, we need to write a script. As in the above case, we use the “Audio Source” component and set Audio Clip, but the “Play when awake” option should be unchecked. Then in the script attached to the object, we create the variable “Audio Source”, assign it to the “Audio Source” component and in the method where we call some action, we play the audio effect using the “Play” method: “AudioSource.Play();”.

In case our object should make a sound after we collect it, we need another method to make it work. Every object disappears after we collect it, so when we attach a sound to an object, it will not play after it is destroyed. To play the sound after collecting some item, we can use the “PlayClipAtPoint()” method of the “Audio Source” class. We also need an additional variable “AudioClip” where we will store our sound effect.

For different scenarios, we should know different methods to play sound effects.

--

--

--

Hi, I’m Damian, a Unity Software Engineer who loves building education and simulation games.

Recommended from Medium

Tips for Writing Readable Code (exemplified)

A Beginner’s Guide to Spatial Processes Package of SBML Version 3 Core 2

Java: Create a Spring Data JPA App with IBM Db2 and FDIC Institutions Data

What is Docker?

Automation of Testing Activity with RPA-UIPath on Microstrategy Grid Reports

Adobe Tech Radar: July 2019

On Testing (My Sanity)

Navigating Git and Github: Part I

Referenced from https://www.etsy.com/au/listing/621508533/abstract-branch-photo-tree-branches

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
Damian Dąbrowski

Damian Dąbrowski

Hi, I’m Damian, a Unity Software Engineer who loves building education and simulation games.

More from Medium

Adding enemies to our greybox Prototype

Ledge Grab System in Unity

How to Win the Race Using Director

Unity : AI [Navmesh implementation (Part II)]