Coding audio

With the Audio Source attached to the collectible prefab, the obvious idea would be to play the sound when a collision occurs between the character and the item.

This can be done by adding a few lines to the Runner script.

In the OnCollisionEnter() function of the script, we write this if statement to check whether the character hit a collectible:

if(c.gameObject.tag == "collectible"){
  Destroy(c.gameObject);
  collected += 1;
  Debug.Log(collected);
}

If we want the audio clip to be played when the character collides with a collectible, we can apparently put the following line inside the if() statement:

c.gameObject.audio.Play();

Unfortunately, we can't do that! If we did, the collectible game object would be destroyed the very moment it begins playing the sound, and the player would hear nothing.

This is a common problem, but there are many solutions to overcome it. The solution we provide is a creative way to achieve the result we want, and it involves using another important Unity asset we didn't mention yet.

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

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