Hello eveyone, i want to make a footstep sound but my code doesn't make the audio work properly

Hello eveyone, i want to make a footstep sound but my code doesn’t make the audio work properly It repeats itself for like infiite times when i press the “W” button. Here is my code:

        private void PlayFootStepAudio()
        {
            if (!m_CharacterController.isGrounded)
            {
                return;
            }
            // pick & play a random footstep sound from the array,
            // excluding sound at index 0
            int n = Random.Range(1, m_FootstepSounds.Length);
            m_AudioSource.clip = m_FootstepSounds[n];
            m_AudioSource.PlayOneShot(m_AudioSource.clip);
            // move picked sound to index 0 so it's not picked next time
            m_FootstepSounds[n] = m_FootstepSounds[0];
            m_FootstepSounds[0] = m_AudioSource.clip;
        }

How can i a make this work properly?

Kind Regards, Cesurix

Thr problem is that most likely you run PlayFootStepAudio() in update and so as long as the character is on the ground, the audio source will play a footstep sound each frame. It depends on the game but if you have animation to the character, you could add 2 events on the animation (1 for each foot) to trigger the PlayFootStepAudio function and if not, you could run this code with a given delay between each step. I will attach the code for the second case

private float lastPlayTime = 0f;
private float delayBetweenSteps = 0.5f;

private void PlayFootStepAudio()
{
	if (!m_CharacterController.isGrounded || Time.time - lastPlayTime <= delayBetweenSteps)
	{
		return;
	}

	lastPlayTime = Time.time
	// pick & play a random footstep sound from the array,
	// excluding sound at index 0
	int n = Random.Range(1, m_FootstepSounds.Length);
	m_AudioSource.clip = m_FootstepSounds[n];
	m_AudioSource.PlayOneShot(m_AudioSource.clip);
	// move picked sound to index 0 so it's not picked next time
	m_FootstepSounds[n] = m_FootstepSounds[0];
	m_FootstepSounds[0] = m_AudioSource.clip;
}

Well, you could change this:

m_AudioSource.clip = m_FootstepSounds[n];
m_AudioSource.PlayOneShot(m_AudioSource.clip);

For this:

 m_AudioSource.PlayOneShot(m_FootstepSounds[n].clip);