without InvokeRepeating.
For example i need sound to play every 4 seconds. So right now it plays several times(sound file shorter than a second) during seconds 4,8,12, and so on. But I need it to play only once per second 4,8,12…
without InvokeRepeating.
For example i need sound to play every 4 seconds. So right now it plays several times(sound file shorter than a second) during seconds 4,8,12, and so on. But I need it to play only once per second 4,8,12…
You can use a coroutine:
var interval: float = 4; // you can change this at runtime if you want function PlayAndWait(){ while (true){ audio.Play(); yield WaitForSeconds(interval); } } function Start(){ PlayAndWait(); ... }
This works fine but accumulate small timing errors, what results in a small but slowing crescent delay from the 4 seconds boundaries (play at 40.6s instead of 40s, for instance, and later play at 201.4s instead of 200s, and so on). If you need a more precise interval timing, use this:
var interval: float = 4; // set the time interval private var timeToPlay: float = 5000; // avoid weird sounds at beginning function Start(){ // adjust timeToPlay to the next interval boundary timeToPlay = Mathf.Ceil(Time.time / interval); } function Update(){ if (Time.time >= timeToPlay){ // time to play? audio.Play(); // yes: play the sound... timeToPlay += interval; // and define the next time } }
This alternative doesn’t accumulate errors, but could produce really annoying sounds at beginning because the sound would be stopped and restarted each frame until timeToPlay reached the current time. To avoid this, timeToPlay is created with a big value, and adjusted at Start to the next interval boundary.