Update and PlayOneShot (audio interval)

Heeey developers :slight_smile:

I have one question - how can i set time between the same audio file?
The thing what i want to do is - While holding key play sound in loop.
this is what i have:

function Update () {
if(Input.GetKey(KeyCode.X)) {
audio.PlayOneShot(sound);
} 
}

Everything would be just fine if sound wouldnt be looped (and started over) every single frame. So the sound isnt anymore sound, but noise (like - trtrtrtrtrtr…)
But the thing is i dont want to play whole audio clip i just want to play 0.5 secs not 0.1 or less like how is it now… So solution wouldn’t be to check if sound is played till end…
I also tried like this:

var timer : float;
if(Input.GetKey(KeyCode.X)) {

timer = Time.time * 0.1; //also tried deltaTime..
if(timer > 0.5) {
timer = 0;
audio.PlayOneShot(sound);

}
}

But no success
Any ideas?

PS.
Audio source is on Player GObj and player have more then one sound, so if i will edit AudioSource component, then also will be edited other sounds… right?

You need to increment the timer, by the amount of time elapsed since last frame, while in your code you set it always to one tenth of time elapsed since scene start. Use:

timer += Time.deltaTime;

instead of

timer = Time.time * 0.1; //also tried deltaTime..

Additionally, you need to:

  1. Declare timer variable outside of Update function

  2. Call audio.Stop() before calling audio.PlayOneShot (otherwise your sounds will stack)