I am using the function Random.range to play random sounds for footsteps. The problem cosists of the fact that the function is selecting, for me, more that 1 sound at once:
I tried to monitor the functionality of Random.Range and the result is that in just 1 sequence isolated by 2 yields I got 4 random numbers. So, the output is 4 sounds started simultaneously.
This is the code(I used IE numerator to use the yields) :
there is a yield of aproximately 1 second so you would expect that temoraryAudio should take every 1 second a new value, but what happens is this :
While walking, in the inspector temoraryAudio changes sounds like nuts (not caring about my yield) and the sounds don’t get to play more that 0.01 sec then it’s changed into another.
What I am actually trying to say is YES. temporaryAudio takes 4 or more values at a time.
EDIT *
Oh an another thing. After I stop moving there are 4 more sounds that will play like that. The 5th is played well and at its full length
My guess is that “simplyMoving == true” is spanning through multiple updates and more than one coroutine is started. Then after first yield in each coroutine (time diff between each corotine could be very small) new audio is played. Maybe you should delay starting another coroutine.
Here’s my script, you can use it if you want.
Replace rigidcontroller with whatever controller you character is using.
It checks the grounded (or isgrounded) on the controller.
using UnityEngine;
using System.Collections;
public class FootStephandler : MonoBehaviour {
public RigidController CharControl;
public AudioClip[] FootStepSounds;
public float waitTime = 0.75f;
public float waitTimeR = 0.25f;
public bool Steping = false;
// Use this for initialization
void Start () {
CharControl = GetComponent<RigidController>();
}
// Update is called once per frame
void Update () {
if(Mathf.Abs(Input.GetAxis("Vertical")) > 0.1 Steping == false CharControl.grounded == true
|| Mathf.Abs(Input.GetAxis("Horizontal")) > 0.1 Steping == false CharControl.grounded == true){
Invoke("FootStep", 0);
Debug.Log("Steped");
}
}
void FootStep(){
Steping = true;
if(Input.GetButton("Run")){
audio.clip = FootStepSounds[Random.Range(0, FootStepSounds.Length)];
audio.Play();
Invoke("ChangeStep", waitTimeR);
}else{
audio.clip = FootStepSounds[Random.Range(0, FootStepSounds.Length)];
audio.Play();
Invoke("ChangeStep", waitTime);
}
}
void ChangeStep(){
Steping = false;
}
}