Search Unity

Stopping a Sound when Player stops moving

Discussion in 'Scripting' started by Gravano, Aug 13, 2019.

  1. Gravano

    Gravano

    Joined:
    Jan 2, 2018
    Posts:
    16
    I'm trying to find the right way to script how to shut off my audio source when my character stops moving, performs another action, etc. I'm trying my own stuff since I finished the Ruby 2D tutorial, and managed to get the walking sound to play somewhat appropriately. Here is the condensed code:

    Code (CSharp):
    1. public class RubyController : MonoBehaviour
    2. {
    3.  
    4. float walkingTimer;
    5. bool isWalking = false;
    6. Vector2 lookDirection = new Vector2(1, 0);
    7. AudioSource audioSource;
    8. public AudioClip acWalk;
    9.  
    10. void Start ()
    11. {
    12.      audioSource = GetComponent<AudioSource>();
    13. }
    14.  
    15. void Update()
    16. {
    17.         float horizontal = Input.GetAxis("Horizontal");
    18.         float vertical = Input.GetAxis("Vertical");
    19.  
    20.         Vector2 move = new Vector2(horizontal, vertical);
    21.  
    22.         if(!Mathf.Approximately(move.x, 0.0f) || !Mathf.Approximately(move.y, 0.0f))
    23.         {
    24.             lookDirection.Set(move.x, move.y);
    25.             lookDirection.Normalize();
    26.             if(!isWalking)
    27.             {
    28.                 isWalking = true;
    29.                 PlaySound(acWalk);
    30.                 walkingTimer = 1.2f;
    31.             }
    32.         }
    33.  
    34.    if (isWalking)
    35.         {
    36.             walkingTimer -= Time.deltaTime;
    37.             if (walkingTimer < 0)
    38.             {
    39.                 isWalking = false;
    40.             }
    41.         }
    42.  
    43. public void PlaySound(AudioClip clip)
    44.     {
    45.         audioSource.PlayOneShot(clip);
    46.  
    47.         while(Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow))
    48.         {
    49.             Debug.Log("While");
    50.  
    51.         }
    52.         Debug.Log("After While");
    53.  
    54.         audioSource.Stop();
    55.     }
    Like I said, I cut out most of the code that should be irrelevant here. The while statement, unfortunately, caused an infinite loop, so I know that isn't right. My idea is that I should be testing for a condition where the player's input axis or key is null or is no longer the normal movement keys. Forgive my poor C# literacy.
     
  2. Boz0r

    Boz0r

    Joined:
    Feb 27, 2014
    Posts:
    419
    How about this?
    isWalking = !Mathf.Approximately(move.sqrMagnitude)
     
    Gravano likes this.
  3. Gravano

    Gravano

    Joined:
    Jan 2, 2018
    Posts:
    16
    Thanks, I will give that a try