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) {

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?


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)

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!