Stop sound on input.getkeyup

This is my script, when i press shift the sound plays and loops but when i release shift it does not stop.

#pragma strict
var SprintSound : AudioClip;
var wdown;
var shiftdown;
audio.clip = SprintSound;

function Start () {

}

function Update () {
if (Input.GetKeyDown (KeyCode.W)) { 
wdown = "yes";
}
else { 
wdown = "no";
}

if (Input.GetKeyDown (KeyCode.LeftShift)) { 
shiftdown = "yes";
}
else { 
shiftdown = "no";
}


if (shiftdown == "yes") {
audio.Play();
}
else
{
audio.Stop();
}
}

Try doing this instead:

if( Input.GetKeyDown(KeyCode.LeftShift) )
{
    shiftdown = "yes";
}

if( Input.GetKeyUp(KeyCode.LeftShift) )
{
    shiftdown = "no";
}

Is there any reason why you’re using a string to handle a true / false state? Why not just use a boolean?

var shiftdown = false;

if( Input.GetKeyDown(KeyCode.LeftShift) )
    shiftdown = true;

if( Input.GetKeyDown(KeyCode.LeftShift) )
    shiftdown = false;

Also, when you think about it, since you’re constantly checking the state of shiftdown at the end of your Update() loop, if shiftdown does not equal “yes” or false in my code’s case, then audio.Stop() is constantly going to be called. Just put the audio.Play() and audio.Stop() in the corresponding if statements:

if( Input.GetKeyDown(KeyCode.LeftShift) )
    audio.Play();

if( Input.GetKeyUp(KeyCode.LeftShift) )
    audio.Stop();

Sure, calling audio.Stop() constantly is most likely returning out of the method if it’s not playing, but that’s still wasted processing. In this particular case, the wasted logic is a completely negligible factor, but sound practice will cause less need for refactoring as you progress.

As the documentation in Unity says for Input.GetKeyDown():

Returns true during the frame the user starts pressing down the key identified by name.

You need to call this function from the Update function, since the state gets reset each frame. It will not return true until the user has released the key and pressed it again.

and for Input.GetKeyUp():

Returns true during the frame the user releases the key identified by name.

You need to call this function from the Update function, since the state gets reset each frame. It will not return true until the user has pressed the key and released it again.

Each of these will only return true during the frame that they were processed, so your code should adjust for that accordingly.