- Home /
Update and PlayOneShot (audio interval)
Heeey developers :)
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?
Answer by ArkaneX · Jan 28, 2014 at 02:06 PM
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)
Thaaaank you. Then timer (without +)= time.deltatime * 0,1... Timer will always be 0,1?
Worked like a charm. Thank you for your time. :)
If you use timer = Time.deltaTime * 0.1, then it will always be equal to one tenth of Time.deltaTime for the current frame. So if your game runs at 60FPS, timer value would be around 0,0017.