Simple Sound Implementation in Unity3d

This is Eric Nielsen with you today on the topic of sound implementation in Unity3D. Besides composing music with Catherine Grealish, I’ve also taken on the duty of adding the music and sound effects in the game. For my part, I have a technical background that has given me some of the groundwork for this task, including extensive work in developing databases, end user tools in Visual Basic, Visual Basic for Applications and various other info-techie endeavors in past careers, so jumping into game audio implementation has been fun and also a little challenging. Fortunately, Unity3D makes the basics super simple, and there is an abundance of examples as well as middleware tools available, some of which we are evaluating for future iterations of the game (more on that in a later post).

To demonstrate the simplicity of implementing sounds in Unity3D, I will outline a quick three step how-to for adding a “one-shot” sound to an event, my example being our main laser cannon sound. One thing we must have in any project with sound is one Audio Listener object, which is by default associated with the Main Camera.

Our first task is to add the sound asset in Unity. Sound files can be placed in the game’s project folder in Assets : Resources : Audio : Source using the Asset : Import New Asset menu item or via the operating system’s file manager. Either way, Unity will recognize them as new assets.Adding Assets

Audio SourcesThe second task is to associate our main gun sound to another game object, in this case, our Player’s fighter ship. We’ll create an Audio Source object within the Player object and then drag a sound file to the Audio Clip field of the new Audio Source object, as shown in the Inspector.  By default, new sounds in the Audio Source object are marked as “Play On Awake” which we will uncheck for this sound.

MainWeaponVariableThe last step gets us into the code. One script in particular, in this case our “Firing” script, is also associated with the Player object, where we can add the new Audio Source variable. Here it is called “MainWeapon,” and the command to play that sound when the weapon is fired, in this case we type in In our code, we’ve added an “if” statement to make sure we’re not trying to play a variable that has nothing associated to it.


Other functions such as AudioSource.playOneShot(), or  Pause and Stop can expand on this basic functionality, and any sort of “round-robin” or randomized clip rotation, or even dynamic mixing of individual sound elements, will either require extra coding, or the use of a middleware tool to take on that workload.

And there we have it – our main gun sound will blast away at the enemy! Stay tuned for more about our future iterations on music, sound implementation and more.