- Home /
Syncing up two GameObjects' timestep
I have two GameObjects that, according to my code, move towards and then attack each other once within a certain range. The effect of the attack is a small upwards/backwards knockback, which, once the target has returned to the ground, results in the two GameObjects moving towards each other again to repeat the cycle.
The issue I'm having is that, even when both of these units are given the same parameters concerning attack range, only one of them will successfully attack, launching the other before it has a chance to respond. It seems to be random which of the two will "strike first," despite their running off of identical scripts. Ideally I'd like them to both successfully attack upon meeting, knocking each other back.
Right now, their attack trigger is a simple Vector2.Distance calculation: "if it's less than the attack range (and attack is not on cooldown), then attack." I had this in FixedUpdate and recently moved it to Update, but the behaviour is the same in either.
Is there a way to ensure that these separate GameObjects do their critical distance calculation on the same timestep? Or is there another way to go about this? Thank you for your counsel.
Answer by StephanK · Mar 19, 2014 at 04:28 PM
Executing of scripts is sequential, so if the first one knocks back his enemy the other one will be out of range when it's his turn (since he got knocked back). The safest way to do this is probably to have the attacker trigger the defendants attack method when he is attacking.
Ah! That's helpful to know. Because I want to have units with varying attack ranges, what I'll probably do is have any attack trigger a distance check on the target which, if it passes (and that unit isn't on cooldown), will result in a response attack (with a flag so as not to trigger an infinite string of such exchanges).
Just to clarify my understanding further: with the above plan in $$anonymous$$d (and the assumption that being the victim of an attack precludes the regular attack option), would two attack methods being called simultaneously be impossible? Or just very unlikely?
Thanks for your response.
*Edit: I just implemented this and it works beautifully. Thanks again (but still curious regarding my above synchrony question).