I have added further to Project 1. I decided to make three more sounds effects. There is now a sound effect for: an enemy getting hit with a bullet, firing a bullet and destroying the environment.
As usual, I opened Audacity and recorded three different tracks. If you would like more info on how I did this, you can check out my previous audio blog.
I then exported all of the tracks and named them Bullet, BulletHit and Rip. Then I moved the exported files into my Unity project.
The first thing to do was to add more public references to the AudioManager script. So now my script looks like this:
Then I can just drag and drop the audio files that I have into the appropriate spot in the Inspector.
Now for the interesting part. To make the audio change pitch when it play, all we need is one line of code.
I put that one line of code in the Attack() function in the Player script, which might seem familiar if you have seen some of my other Project 1 blogs.
It is line 62 that does all the work. When the bullet shoots, it travels toward the mouse cursor and plays the ‘bullet’ sound effect at a pitch that ranges between 0.6 and 1.4 (with 1 being the original pitch). The pitch changes every time the player shoots a bullet.
However this setup has a flaw. Since all audio plays through audioManager.audio, every sound effect is going to play at the same pitch as the last bullet fired. There are two ways to solve this and one way takes much longer and requires more work than the other.
The more difficult option is to add an extra line of code to all scripts that play audio. In this case I have five other audio clips whose pitch I don’t want to change. This means that every time I use audioManager.audio.PlayOneShot() (the same function is on line 63 in the code above), I need to add the following code on the line above it:
This line will change the pitch back to 1 meaning that the next line, the line to play audio, will play at the normal pitch.
The easy fix is to add an extra AudioSource to the AudioManager GameObject. After doing so, the AudioManager code will also need to change to the following:
The Start() function that found the AudioSource will not work anymore since there are two AudioSources. So instead, we remove the Start() function and add another public reference for the second AudioSource. Now we can just drag and drop the AudioSources in the Inspector.
Finally, lines 62 and 63 in the Player script change to:
Instead of playing the audio through audioManager.audio, it now plays through the second AudioSource audioManager.bulletHit. Also, only the Pitch of the second AudioSource is change. This means that all audio played through the first one will not have a change in pitch.