GameDev : Audiosource (Part II)!
We have a good background track, but we need more sound in our game : Laser, Explosions, maybe when we collect Powerups.
How set up the audio for one single sound?
The basic logic is the same, we have the Audiosource component, we need to attach it to the right object, and through the code we take a reference to Audiosource, and there are many methods that allow us to set the sound.
If you think, at LOGIC LEVEL, Audiosource works like Animator.
When we use Animator, we have to add the component, then inside the script we take a reference to it and we call the method we need where we need, right?
Audiosource works exactly the same, we add the component, we take the reference, we call method where we we need.
Now, we add Audiosource to the Player, toggle off Play on Awake, drag Laser sound on Audiosource.
Open its script, we take reference and check for NULL Reference in Start.
After all of this things, we need to Play the clip. Where?
Well, we press Space Bar and we can shoot.
We have the FireLaser() method
After the check for nextFire, and after the visual effect (the Instantiate part), we call the sound effect.
Tip : light is faster than sound, so we put audio always after the visual effects.
To find Play() method, I simply go to the documentation, and search for Audiosource
As always, documentation is our best friend!
In my case everythings works fine, everytime I press Space Bar I shoot Laser and I hear the sound.
Now, let’s try and see how works with AudioClip
The reference remain the same, but we need to add a FIELD to AudioClip and Serialize it
In Player Inspector now drag the audio file
Now, pay attention to this passage :
In the AudioSource NULL check, we add an ELSE Statement
here we use a PROPERTY of Audiosource component.
Let’s try to break the logic into small parts: when we refer to Audiosource, we can enter in that component and MANIPULATE IT.
If we look at Inspector
There is AudioClip field.
We can directly access to every field you see here through the AudioSource component.
So after we drag the sound effect into Player, we can access to AudioClip field thanks to AudioClip reference.
I know, we not talk yet about “Properties” but I will make it soon.
The logic behind them isn’t that hard to understand: when we create a variable, we can ASSIGN that variable to a value, right?
For example “lives”.
We assign the value to 3.
This is almost the same concept, we have AudioSource and we try to manipulate what’s in its field right?
Because we drag an audio file into it.
So in the check we simply say:
“If Audiosource is NULL, give me an error Log.
But if it’s not NULL, Play the clip that we assign.”
I hope this is little bit clear now, and we make same result with more than one way.