- Home /
Calling a function repeatedly in Update for a given duration
The simplest example of the feature I want is Debug.DrawRay(start, dir, color, DURATION)
, where the key point is the DURATION
. Using this, I can call call this function from within an event handler (like Input.GetKeyDown
) and have it render for a given duration. Now my question is, what are the best solutions for doing this with general code, with as little boilerplate as possible?
I know I could just create an ad-hoc function that stores the time, and then count down in Update()
and run the behavior, but this just adds unnecessary bloat to the code. Some assets (like ALINE) provide this also out of the box, though they're not really general purpose.
The way I imagine the API is something like Run.WithDuration(() => ..., 1.5f)
where this call stores the lambda function in some intelligent way, and then calls it repeatedly during Update()
for 1.5 seconds. In some sense any tweening library (like DOTween) does this as well, but again they're a bit specific to a particular problem.
Is there any existing library or asset (I don't really care if I have to pay), or even a pattern that people implement themselves (I don't really mind implementing it if it's reasonable), that is stable and handles all the cases like editor reload, pause, etc? (and ideally even works in the editor?)
I know I could make a barebones version of this just having List<Tuple<Action, time>>
or something like that and run a single global loop over this, but the main point of my question is to find a proper solution to this problem, not just a random hack that will break in unexpected ways. The key feature is also not having to define any extra variables or functions per each such call.
Your answer
![](https://koobas.hobune.stream/wayback/20220613001129im_/https://answers.unity.com/themes/thub/images/avi.jpg)