I have wrote this script hoping that it would play my footstep sound when w or s is held down but I have a lode of errors, is there any easier way to do this or am I nearly there?
var footsteps : AudioClip;
var waitTime = 0.5;
function Update () {
if(Mathf.Abs(Input.GetAxis("Vertical")) > 0.1){
yield WaitForSeconds(waitTime);
audio.Play(footsteps);
}
}
You can’t use yield inside Update or any other periodic routine (LateUpdate, FixedUpdate, OnGUI), but a very similar approach can work if started at Start (yes, Start can use yield!):
var footsteps : AudioClip;
var waitTime = 0.5;
function Start () {
// create an infinite loop that runs every frame:
while (true){
if (Mathf.Abs(Input.GetAxis("Vertical")) > 0.1){
yield WaitForSeconds(waitTime);
audio.Play(footsteps);
}
yield; // let Unity free till next frame
}
}
This implements a kind of private Update: the code inside the while infinite loop is executed every frame, then the yield instruction lets Unity free to take care of its business until next frame.
you can’t use WaitForSeconds in Update, because it’s called every frame, but otherwise this should work, just remove that line…
but if you really want the pause, you can create a coroutine to call from Update:
var footsteps : AudioClip;
var waitTime = 0.5;
function Start(){
audio.clip = footsteps;
}
function Update () {
if(Mathf.Abs(Input.GetAxis("Vertical")) > 0.1)
WaitFootsteps();
else
makeSound = false;
if(makeSound)
audio.Play();
}
function WaitFootsteps(){
if(!makeSound){
yield WaitForSeconds(waitTime);
makeSound=true;
}
}
this should pause before the FIRST step, I assume that’s what you wanted… If you’re just trying to pause between EVERY step, just loop the clip and make it have a half-second pause in the actual audio clip, that would make more sense…
var Walk : AudioClip;
function Update () {
if (Input.GetKey("w") || Input.GetKey("a") || Input.GetKey("s") || Input.GetKey("d"))
{
if(!audio.isPlaying) // this line may not even be necessary
audio.Play();
audio.loop = true;
}else
audio.loop = false;
}
When you press either w,a,s or d then it will play the sound you decide to play.
Hope this helped