- Home /
Activate audio when the key is pressed.
Hey.. i did so for activate audio only when the key is pressed, and if relase it, the audio should be turned off. But this way doesn't work... why?
public AudioClip Audio;
void Awake() { audio.loop = false; }
void Update() {
if (Input.GetKey (KeyCode.D))
{
audio.clip = Audio;
audio.Play ();
}
else{
audioStop();
}
What is the "audioStop()" function?
It seems like you might have multiple problems. For one, "Input.Get$$anonymous$$ey" will return true for every frame the key is held down. This means that every frame, you will be telling the audioclip to start over and play again.
What you want would be something more like:
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.D))
{
audio.clip = Audio;
audio.Play();
}
if (!Input.Get$$anonymous$$ey($$anonymous$$eyCode.D))
{
audio.Stop();
}
Answer by RoelfMik · May 16, 2014 at 04:52 PM
This should work! If you have any other questions, feel free to ask :]
void Update()
{
if (Input.GetKey(KeyCode.D))
{
if (!audio.isPlaying)
{
audio.Play();
}
}
else
{
audio.Stop();
}
}
Your answer
Follow this Question
Related Questions
How to stop just one AudioClip? 1 Answer
Stop audio loop 1 Answer
Stop music playing after changing scenes. 1 Answer
Sound stops when object is destroyed 6 Answers