- Home /
footstep sound effects sprinting fix
so i have this very bad code of a footstep sound effect that activates a sound each step when grounded but thats it, ive tried researching on how i can multiply the sound each step when sprinting but i couldnt find any solution, any tips on how i should go with this? what code should i add to mutiply the sound when sprinting?
public Rigidbody rb;
public playermovement movement;
public AudioSource audioSrc;
void Start()
{
rb = GetComponent<Rigidbody>();
movement = GetComponent<playermovement>();
audioSrc = GetComponent<AudioSource>();
}
void Update()
{
if(movement.isGrounded == true && rb.velocity.magnitude > 2f && GetComponent<AudioSource>().isPlaying == false)
{
GetComponent<AudioSource>().Play();
}
}
Answer by CodesCove · Dec 10, 2021 at 08:30 PM
I'm not writing the whole code here but I give you some pointers and example..
You need loop the audio by the step frequency you have and the clip should include audio for one step only. This is something you need to sync with the animation speed or the actual speed of the character.
Anyway the principle is to implement something like this (you need to tweak it for your purposes of course):
public AudioSource audioSource;
public AudioClip audioClip;
public float loopsPerSecond = 2;
private void StartAudioLoop()
{
StopAllCoroutines();
StartCoroutine(PlayAudio());
}
private void StopAudioLoop()
{
StopAllCoroutines();
}
private IEnumerator PlayAudio()
{
while (true)
{
if(loopsPerSecond > 0)
{
yield return new WaitForSeconds(1 / loopsPerSecond);
audioSource.PlayOneShot(audioClip);
} else yield return null;
}
}
In the above example the loopsPerSecond would be the foot step audio playback per second.
Notice that PlayAudio is started as Coroutine (https://docs.unity3d.com/Manual/Coroutines.html) and will loop itself and you need to start in only one time.. so do not try to call StartAudioLoop() in every frame inside inside Upate.
PS: in your code you are already caching the audio source, don't get it inside Update (called every frame!), it's very inefficient..