I’m looking for the (1) most performant (inc. GC friendly) approach to scheduling an asynchronous callback (per-Behaviour Tree ticks). I need to schedule both (2) “in N seconds from now” and (3) “next frame” however I also need to (4) add scheduled times in. (5) Any given Behavior Tree should only be ticked once per frame. (Requirements numbered to aid referring back to them.)
There’s an added complexity to (5):
Req (3) (“next frame”) is mostly due to the work in one tick requiring another tick – just not in this frame. However sometimes an externally prompted tick (e.g. from a pathfinding result) hits in the same frame as a time-scheduled tick. When this happens order matters: it’s fine to skip the time-scheduled one if we already ticked this frame but the other way round, the prompted-by-work-done-in-this-frame one needs deferring to the next frame. To start with I’m checking in the
tick() to see if already done this frame and deferring any if so. This does occasionally result in ‘backed-up’ ticks (ticking every frame for 5 frames when we get several that attempt to tick at the same time and they all serialize pointlessly). Still need to fix this.
I started with by testing the obvious naive approach
Invoke(methodName, delay) but struggled with (3) to find a value of
delay that guarantees 1 frame later (
Time.deltaTime sometimes works, sometimes calls in the same frame = disaster). Obviously it’s likely only good for (2).
Coroutines don’t seem to fit since if one is already in
WaitForSeconds(5), we can’t insert a new tick (4) since the Coroutine would need interrupting (stopping and recreating?) and Coroutines aren’t great for GC anyway)
I tried the usually excellent DOTween’s
InsertCallback() but same problems as
The only other solution I can think of is per-frame checking, ideally a single one between all Behaviour trees. Probably a time-ordered
List with the tree to tick, minimum time at which to call (for req 2), optional minimum frame number (for req 3). I’ll need to search and insert for (4).
This all seems rather messy which makes me worry I’ve missed other potential solutions.