Unity: Scripting sound effects

First we need to add an audio source to the Player object. We also want to uncheck ‘Play On Awake’ as we need to script when sounds are played.

Next we need to alter our Player script.

We add a an AudioClip for the laser sound, and one for the AudioSource.

We use GetComponent<> to get the Audio Source at Start() and check for null.

In the shooting method, in both of our if else-if statements we assign the laser clip to the Audio Source then play the assigned clip. This will allow us to use the same Audio Source for different clips in future if needed. If we find that we only use the laser sound for the Player’s Audio Source, then we can assign this in Start() later on.

Back in Unity we assign our laser sound to the Laser Audio Clip on our player.

Now when we play the game, this scene sounds like a fierce space battle rather than a silent movie!

This same process can easily be repeated for powerups and explosions as well.

--

--

--

Software developer in the field of Unity and C#. Passionate about creating and always driven to develop.

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

Recommended from Medium

Tyranny of Structuredness

Is JS and Python justified in their popularity?

Add shortcuts to your PWA

Algorithmic Game Theory with Nashpy

Mining Program Update #7 (2021/10/1~12/16)

How to control 3 Macs from one

A Day Spent In Navgurukul, Bangalore

Lawyers in Utah

lawyers in utah

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
Ian Plumpton

Ian Plumpton

Software developer in the field of Unity and C#. Passionate about creating and always driven to develop.

More from Medium

Spawning Enemies

Creating a material in Unity

Unity Performance Optimization Ⅴ: Lua Scripts Optimization

Simple Player Movement in Unity