Multithreading OverlapSphere with JOBS

How can I JOB-ify something as simple as this:

[SerializeField] Collider[] hitColliders;
void Update()
{
    hitColliders = Physics.OverlapSphere(transform.position,30f);
}

Now, I know OverlapSphereCommand exists

But I’m clueless on how to properly implement it with Burst. The example code in the link also crashes my editor whenever I have more than 5 objects with the same script, oddly.


I am a little confused with the JOBS coding workflow, I’ve watched a few videos but I can’t implement anything other than basic number operations…

Basically, I just wanna know how can I turn something like the code I showed earlier into multithreaded code. And it should run on multiple objects with the same script.

Please enlighten me, maybe with an example I’ll finally be able to understand!

It would be something like this:

using UnityEngine;
using Unity.Collections;
using Unity.Jobs;

public class SphereOverlap : MonoBehaviour
{
    [SerializeField] LayerMask _layerMask = ~0;    
    
    const int k_max_hits_per_command = 3;
    NativeArray<OverlapSphereCommand> _commands;
    NativeArray<ColliderHit> _results;
    JobHandle _dependency;
    
    void Awake ()
    {
        _commands = new ( 1 , Allocator.Persistent );
        _results = new ( _commands.Length*k_max_hits_per_command , Allocator.Persistent );
    }

    void OnDestroy ()
    {
        _dependency.Complete();
        if( _commands.IsCreated ) _commands.Dispose();
        if( _results.IsCreated ) _results.Dispose();
    }

    void FixedUpdate ()
    {
        // complete the jobs that was scheduled last update:
        _dependency.Complete();

        // make productive use of the results:
        foreach( var hit in _results )
        if( hit.collider!=null )
        {
            Debug.Log( hit.collider.name );
        }

        // prepare new jobs:
        _commands[0] = new OverlapSphereCommand(
            point: transform.position ,
            radius: 30f ,
            queryParameters: new QueryParameters( layerMask:_layerMask , hitTriggers:QueryTriggerInteraction.Ignore  )
        );
            
        // schedule new jobs:
        _dependency = OverlapSphereCommand.ScheduleBatch( _commands , _results , minCommandsPerJob:1 , maxHits:k_max_hits_per_command );
    }
}

This is a slight misunderstanding. Burst implementation is decided by a person who writes the particular IJob and this is not such case as OverlapSphereCommand was written by Unity dev team.