Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Footsteps sound like a machine gun

Discussion in 'Scripting' started by Grymmjow, Nov 24, 2017.

  1. Grymmjow

    Grymmjow

    Joined:
    Mar 21, 2014
    Posts:
    5
    I have a code to make the footstep audio play while my player is walking. But whenever I hold down the W key, the audio just starts repeating like crazy, and I know that the reason this happens is because it's being called on the update. What I want to know is how can I make it play in the way I want? It doesn't have to be perfect, just a simple loop will do. Thanks in advance.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Footsteps : MonoBehaviour {
    6.  
    7.     public AudioClip footsteps;
    8.     public float volume;
    9.  
    10.     // Use this for initialization
    11.     void Awake () {
    12.         volume = 100;
    13.     }
    14.  
    15.     // Update is called once per frame
    16.     void Update () {
    17.         playFootsteps ();
    18.     }
    19.  
    20.     public void playFootsteps(){
    21.         if (Input.GetKey (KeyCode.W)) {
    22.             AudioSource.PlayClipAtPoint(footsteps, transform.position, volume);
    23.         }
    24.     }
    25.  
    26.  
    27. }
    28.  
     
  2. hasanbayat

    hasanbayat

    Joined:
    Oct 18, 2016
    Posts:
    629
    You can use Coroutines in this case and use WaitForSeconds to wait and then play the sound.

    Thanks.
     
  3. Grymmjow

    Grymmjow

    Joined:
    Mar 21, 2014
    Posts:
    5
    I have tried using Coroutines and it still didn't work, could you maybe show me the correct way to do it? Maybe the way I was writing was wrong.
     
  4. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,294
    You usually want to tie footsteps to animations, either through animation events or by looking at the position of the feet.

    For what @hasanbayat is suggesting, it'd be something like:

    Code (csharp):
    1. private Coroutine footsteps;
    2.  
    3. void Update() {
    4.     if (Input.GetKeyDown(KeyCode.W))
    5.         footsteps = StartCoroutine(Footstepsounds());
    6.     if (Input.GetKeyUp(KeyCode.W))
    7.         StopCoroutine(footsteps);
    8. }
    9.  
    10. IEnumerator Footstepsounds() {
    11.     while(true) {
    12.         AudioSource.PlayClipAtPoint(footsteps, transform.position, volume);
    13.         yield return new WaitForSeconds(.2f); //or however long
    14.     }
    15. }
    That will cause tapping W to play the sound repeatedly, though, which might not be what you want.