Basic Footstep Script But I am Puzzled

Hello reader,

I am grateful to you in advance for your patience as you will come to see that the script in question is as basic as they come. Your input in helping me understand why the code isn’t working and how to make it work without making things too complex would be most appreciated (I’m a newbie).

	// Update is called once per frame
	void Update () {
        AudioSource audio = GetComponent<AudioSource>();

        if (Input.GetKeyDown(KeyCode.W)|| Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.D))
        {
            audio.Play();

        }
        else
        {
            audio.Stop();
        }
    }

You will see from the script that in theory the game should play a sound when any of the keys responsible for moving the character (WASD) is pressed and when not pressed, the audio should stop. The actual outcome is that no audio plays at all.

Help?

K

Achieved what i wanted with the following script:

        if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.D))
        {

            isWalking = false;

        }

        else
        {
            isWalking = true;
        }

        if (isWalking == true)
        {
            audio.Play();
        }

But of course none the wiser why the code in my OP didn’t work.

@kyasul

Try this

public AudioClip footStepSFX;
private AudioSource audioSource;

void Start ()
{
	if (audioSource == null)
	{ // if AudioSource is missing
		Debug.LogWarning("AudioSource component missing from this gameobject. Adding one.");
		// let's just add the AudioSource component dynamically
		audioSource = gameObject.AddComponent<AudioSource>();
	}
    audioSource.loop = true; // set the audioSource always to loop when playing
}

// Update is called once per frame
void Update ()
{
    if ((Input.GetKeyDown(KeyCode.W)) || (Input.GetKeyDown(KeyCode.A)) || (Input.GetKeyDown(KeyCode.S)) || (Input.GetKeyDown(KeyCode.D)))
    {
        if (!audioSource.isPlaying)
        {
            audioSource.PlayOneShot(footStepSFX);
        }
    }
    else if (audioSource.isPlaying)
    {
        audioSource.Stop();
    }
}