Adding Sound to the Jump Event

While we could also use an animation event to trigger our jump sound effect, it’s important to have immediate feedback for an action like this. As the jump animation may loop based on the player’s duration in the air, an event would also likely cause the sound effect to play more than once. Accordingly, we’ll play the sound directly from the script, as shown in Listing 11.3.

Listing 11.3 Adding Jump Audio to the PlayerController Script

public AudioClip jumpSound;void Update (){  if(Input.GetButtonDown("Jump"))  {    if(isGrounded == true)    {      this.rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x,0);      this.rigidbody2D.AddForce(new Vector2(0, jumpForce));      this.anim.SetTrigger("Jump"); ...

Get Learning 2D Game Development with Unity®: A Hands-On Guide to Game Creation now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.