I’m learning Unity, and I wanted to fire evenly spaced bullets at a predetermined interval. Consider, for instance, a function that accepts these two inputs:
bulletCount: 5
interval: 0.2f
This would mean fire five bullets over the course of one second, spaced out every 0.2 seconds. So you’d get 5 bullets over the course of one second, evenly spaced.
My code looks like this:
IEnumerator _MakeChain(string type, float speed, float angle, int clipSize, float delay) {
for (int shot = 1; shot <= clipSize; shot++) {
ShootBullet(type, speed, angle);
yield return new WaitForSeconds(delay);
}
yield return null;
}
The result of this code is, well, some unevenly spaced bullets:
The first bullets are always bunched up, for instance, but if you look closely you can see the others are also not evenly spaced.
Is this just a limitation of Coroutines and WaitForSeconds, or am I doing something wrong? I reached for Coroutines because of these two facts:
- Enemies need to be able to start multiple of the same type of “chain” of bullets at once
- The chains of bullets end after a set number of shots
It seems like it would be a headache to try to manage this with InvokeRepeating
, since those go indefinitely, and there’s no fine-grained control over canceling these on a per-invoke status (as I understand it, canceling the invoke will cancel all ongoing invocations of the same method).
I read that WaitForSeconds can be off by a few frames, so for really “tight” spacing it might be off. I wouldn’t expect that for time frames around 200ms though for a game running at 60fps, given that each frame is an order of magnitude smaller than the delay time that I’m passing. The first few bullets look to be about at least 100ms off. Is WaitForSeconds really that unreliable?
I’m sure this is some basic stuff, but I looked around and didn’t see anything in particular that stood out as a possible fix. Is there a common approach to get around this? Thanks!