- Home /
Timeout after sound play
Hi, guys!
My code to reproduce a sound when pressing key:
#pragma strict
var audio01 : AudioClip;
function OnGUI() {
var e : Event = Event.current;
if (e.isKey) {
audio.PlayOneShot(audio01);
}
}
But if not to clamp for a long time at all the button, the sound is looping.
What it is necessary to add that the sound play only once when pressing one key?
Thanks!
Answer by CodeMasterMike · Jan 24, 2013 at 12:53 PM
When playing a sound when the user is pressing a button, I would use the input class instead of the Event. The event resets itself after each time, and therefor you can get a button is pressed event at least once every frame. So it is not very suitable for this type of input.
So I recommend you using input instead:
void Update()
{
// play the sound once when a button is pressed.
if(Input.anyKeyDown == true)
{
audio.PlayOneShot(audio01);
}
}
The code above plays the sound one time when a button is pressed down. To be able to play that sound again, the user has to release the button and press down a button again. Look at the Input documentation for more information and options.
Good luck!
Your answer
Follow this Question
Related Questions
repeated player collisions 1 Answer
make sound work 0 Answers
Background Music 2 Answers
How to Have a Random Interval in an Array in between Sounds being Played? 1 Answer
Sound on keypress, not working 2 Answers