RaycastCommand.ScheduleBatch with List<RaycastCommand>

It happens to me that I don’t know the amount of raycasts upfront when scheduling the job. The raycasts are built by different job, which is not finished yet.

I’m left with two options:

  • Synchronize on the main thread, read output of the previous job and Schedule raycast job
  • Do conservative estimate of amount of raycasts needed and schedule raycast with preallocated array
    (which will be filled by job)

Both approaches are bad, in the first case it introduces extra sync point, I need to find a good place in the PlayerLoop where I should wait for the job and schedule raycasts.

In the second approach I might submit a LOT of empty raycasts, which get skipped by physics (zero length). I haven’t tested the performance implications of that yet. The problem here is the worst case. In average cases, I might need 10 raycasts, but in extreme case when there are a lot of enemies nearby player, it can go to thousands. Doing 990 “empty” raycasts every frame just because I might need 1000 sometimes seems bad.

Proposed solution
Allow us to schedule Raycasts with RaycastCommands in List, so the actual number of raycasts can be determined when starting the job.

Alternative might be to still use arrays, but supply the count parameter as NativeReference for example, instead of Array.Length.

Another alternative would be to allow scheduling the raycasts job from other job. (I think scheduling job from job is not allowed for good reasons now).

Same applies for SpherecastCommand and possibly others.

Oh, actually allowing to schedule raycast job from other job might be ideal case.
Consider this use case.

    [BurstCompile]
    public struct RaycastJob : IJob
    {
        [ReadOnly] public int MinCommandsInBatch;
        [ReadOnly] public NativeReference<int> CommandCount;
        [ReadOnly] public NativeArray<RaycastCommand> Commands;
        [WriteOnly] public NativeArray<RaycastHit> Results;

        public void Execute()
        {
            RaycastCommand.ScheduleBatch(Commands.GetSubArray(0, CommandCount.Value), Results, MinCommandsInBatch).Complete();
        }
    }

There are no issues with dependencies, because job is scheduled and waited immediately.
I’ve read in the recent blog post, that Job system internally allows scheduling jobs from other jobs.

Current result
UnityException: ScheduleRaycastBatch can only be called from the main thread.