Correct way to use job system with invoke repeating using lots of objects that have work to do?

Saw this question on Reddit, but it didn’t really get an answer, so thought I would post it here to see, as I’m curious on how to efficiently do this with the Job System myself.

"Let’s say I have 5,000 cubes in the world that all have a script on them. Let’s say the script has functions to increment a counter, and change the color of the cube randomly. Nothing really intensive, but more could be going on.
All those cubes need to be updated once every second. I will be using “InvokeRepeating” to call a function that loops through all 5,000 cubes and calls 2 functions on each one… “increment”, “changeColor”.
Is this a good candidate for the job system?
Would I simply put the function that gets invoked into a job?
What if I need to make sure that each cube is updated before the next invoke happens? For example; let’s say I add more cubes and reduce the repeating time. Would I create a job for each cube, or still use one job for the whole invoke?"

That very last question interests me. I have groups of unique objects (i.e 1,000 cubes, 500 spheres) that get repeatably called (similar to using InvokeRepeating) every .250ms. The total amount of these objects will grow over time, and the work each of these objects need to do could be nothing, or something. The work my objects need to do isn’t really heavy, but there could be lots that need to do something.

Is it efficient to create a job for each object, or 1 job for all groups of objects?

I also need to make sure that the work my objects do is finished before they get repeated again.

Thanks

You’d use IJobParallelFor (or maybe IJobParallelForBatch?). When you schedule that job, it automatically takes care of breaking up the workload into multiple jobs for you - not one job per item, but processing a range of items in each job - so you just write your Execute() function to process a single entry and it will call that in a loop for you automatically. So you’re only creating and scheduling one job, but the system automatically takes care of turning that into multiple separate jobs under the hood for you.

When you schedule the job, it will return a JobHandle that you can hold on to. Then, the next time you schedule the job, you pass in the JobHandle from the previous one as a dependency. That way it guarantees that the next one will not run until the previous one has finished.

1 Like

Ah nice, makes sense as well. Thanks a lot