- Home /
AudioSource does not work for some reason
Hi all, I am using the following code to initialise a sound playing:
var sound: AudioSource;
var sound: AudioSource;
function Update () {
if (Input.GetKey (KeyCode.W))
{
sound.Play();
}
if (!Input.GetKey(KeyCode.W))
{
sound.Stop();
}
}
For some reason, even though I am using this exact same method to initialise another sound (which works fine), this does not work. I have tried GetButtonDown, and GetKeyDown as well and neither of these work. If I switch the code to the following:
var sound: AudioSource; var sound: AudioSource; function Update () { if (Input.GetKey (KeyCode.W)) {
}
if (!Input.GetKey(KeyCode.W))
{
sound.Play();
}
}
the sound plays a sudden burst at the beginning for about half a second and then stops, but if I push W down it plays. Unfortunately the sudden burst is very offputting so I cannot use this method. Also if I deselect the game (in windows) the sound loops continuously. Can someone tell me what I am doing wrong as I am deeply confused. :-(
Thanks.
Answer by DaveA · Apr 28, 2011 at 08:12 PM
GetKey is true while the key is held. If you want it to start when they hit the key, use GetKeyDown. If you want it to stop when they release the key, use GetKeyUp
But doesnt !Input.Get$$anonymous$$eyDown do the same as Input.Get$$anonymous$$eyUp?
Your answer
Follow this Question
Related Questions
Mute audio with GetKeyDown 0 Answers
Change view if key is pressed 4 Answers
Checking if a key has been pressed twice in quick succession 4 Answers
Walking and Running Script not working. 1 Answer
Input.GetKey question 1 Answer