Unity 3D: Footstep sounds looping the first few milliseconds instead of playing the full sound then looping

Viewed 515

When I move in game, instead of my sound being played in full, it is playing just a few milliseconds on a loop.

Here's my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Footsteps : MonoBehaviour
{
    public AudioSource audioSource;

    public PlayerMovement pM;

    void Start()
    {
        audioSource.Stop();
    }

    void Update()
    {
        PlaySound();
    }

    public void PlaySound()
    {
        if (Input.GetKey(KeyCode.W))
        {
            audioSource.Play();
        }
        else
        {
            audioSource.Stop();
        }
    }
}

Video Example.

Any suggestions would be greatly appreciated!

2 Answers

As @Jamarin mentioned, you can use the moving keys to add the footstep sound.

I just added a list with all moving keys to give a complete solution.

using System.Collections.Generic;
using UnityEngine;

public class Footsteps : MonoBehaviour
{
    List<UnityEngine.KeyCode> keys = new List<UnityEngine.KeyCode>();

    void Start()
    {
        keys.Add(KeyCode.W);
        keys.Add(KeyCode.S);
        keys.Add(KeyCode.A);
        keys.Add(KeyCode.D);
        keys.Add(KeyCode.UpArrow);
        keys.Add(KeyCode.DownArrow);
        keys.Add(KeyCode.LeftArrow);
        keys.Add(KeyCode.RightArrow);
    }

    void Update()
    {
        if (keys.Exists(key => Input.GetKeyDown(key)))
        {
            // PLUS: Change footstep sound to simulate a different kind of footstep.
            GetComponent<AudioSource>().volume = Random.Range(0.8f, 1);
            GetComponent<AudioSource>().pitch = Random.Range(0.8f, 1.1f);

            GetComponent<AudioSource>().Play();
        }

        if (keys.Exists(key => Input.GetKeyUp(key)))
        {
            GetComponent<AudioSource>().Stop();
        }
    }
}

Reference:

https://www.youtube.com/watch?v=ih8gyGeC7xs

Related