- Home /
Multiple batches of raycasts between frames at regular intervals
In order to control some peripheral electronics, I need to do batches of raycasts at a rate much higher than the needed FPS.
I'd also like these batches of raycasts to happen at regular intervals, assuming the whole thing can be completed at the right set by those intervals (I can figure out the code to skip some batches in case the raycasting took to long myself).
I thought of using invokeRepeating
to schedule the jobs and do cleanup after them (calculations on the results), but it occurred to me I'd have nothing else for the main thread to do in the meantime, and so Complete()
would cause the main thread to wait for the jobs to complete and the performance improvement might be wasted.
To that end, I had 2 alternative solutions:
Have two jobs running forever; one
IParallelFor
for the raycasting, and another one to do the cleanup. The cleanup job would uselock
and sleep to make sure things aren't happening to quickly (or to skip if the previous raycast batch took to much time and spilled over to the time meant for the next batch of raycasts), and any time the lock is released, the batch of raycasts will be performed again while the cleanup job waits to take back the lock. I don't know much about multithreading but this seems to me like a bad idea.Schedule a chain of jobs: if
A
is the raycasting job andB
is a cleanup job, usedependsOn
to scheduleA -> B -> A -> B ...
, withB
stalling (by sleeping) if needed, to ensure things don't happen to quickly/to skip over if the previous batch of raycasts ran too long. This one feels less bad than the previous one, but it basically means I just create a long chain of waiting jobs and keep adding to it to keep the whole thing going as long as the game is running. Which feels... weird.
Is there a better way to do this? If one could start a job from within a job, I would just useinvokeRepeating
from one job to start the batched raycastingIParallelJobs
, and the job could wait for it to complete without holding up the main thread.
Your answer
![](https://koobas.hobune.stream/wayback/20220613040644im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
What threads are used in a scene? 1 Answer
C# Raycast Code not working 2 Answers
Jobs running over multiple frames 1 Answer