Sound effects

To play sound effects within our game, we will make an event-based system so that playing the sound effects will be very easy. Sound effects are what bring your items, events, and characters to life! They give your gun the loud bang you would expect, the grunt from your character as they climb a wall, and the notification sound that you get when you hover over an option in the menu. Sound effects add to the immersion of your game and playing them can be very easy.

Creating the script and variables

Our first step in playing sound effects will be to create the C# script and name it SFX_Manager. Next, we will need a few variables; add these to your script:

public float sfxVolume = 1.00f;
public AudioClip Run, Spell, Strike;
public GameObject RunSource;

The first variable should look familiar by now. We will use it for the volume. Next, we create a few audio clips. For this chapter, we will use three specific sound effects for testing purposes. The last variable is a GameObject that will be used to play the running sound effect. Next, let's assign the volume of our sound effects; add this to your Start function:

public void Start()
{
  audio.volume = sfxVolume;
}

Now that we have the volume established, let's add the functions to play our sounds:

public void Run()
{
  if(!RunSource.audio.isPlaying)
  {
    RunSource.audio.clip = Run;
    RunSource.audio.Play();
  }
}

public void Spell()
{
  audio.clip = Spell;
  audio.Play();
}
  
public void Strike()
{
  audio.clip = Strike;
  audio.Play();
}

These functions will be the ones you will call to play a sound effect. To play the run sound effect as a looping sound, we check to make sure that the sound has played out before we play it again. This gives the illusion of a looping sound effect. To play the rest of the sounds, we just assign the clip property and play it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.141.75