Is it possible to CalculateDistance inside a JobComponentSystem?

I'm starting to implement boids using ECS, Jobs, Burst and the new Unity Physics, but I'm getting stuck right at the beginning.

Here is the code of the System:

5195438--516446--upload_2019-11-20_16-55-7.png

When I try to run CalculateDistance from inside a job, the following errors occurs:

5195438--516437--upload_2019-11-20_16-51-53.png

5195438--516440--upload_2019-11-20_16-52-19.png

It looks like a problem in using the AllHitsCollector the way I'm using, but I don't understand what am I doing wrong.

Also, should I dispose the collector after using it, like a NativeContainer? If yes, how?

5195438--516443--upload_2019-11-20_16-53-8.png

Hi, this is the sort of error you see when dependencies between jobs are not set up correctly.

First you should mark the CollisionWorld field of BoidsSystemJob as [ReadOnly], otherwise it can't run on parallel with anything else that reads the physics world.

Next make sure you know when this system is running in relation to other systems. The entity debugger will show you the order. The best thing to do when querying a physics world is schedule the system after BuildPhysicsWorld, using [UpdateAfter(typeof(BuildPhysicsWorld))].

That may be enough to fix your scheduling errors.

You don't need to dispose the collector, but you do need to use its constructor which takes a NativeList provided by you - not the default empty constructor. Or just use the version of CalculateDistance() which take a NativeList directly.

Hey, Rory, thanks for the help. It worked like a charm!

The main problem was the lack of the ReadOnly attribute on the CollisionWorld, I believe.

Regarding the collector, I'm confused. If I need to create and dispose the NativeList event if I'm going to use it in a collector, why should I need a collector for?

5198174--516854--upload_2019-11-21_11-31-17.png

Collectors are a low level thing to define the behavior of queries. We have some built in collectors for common behaviors: collecting all hits (the one you are using); collecting only the closest hit; or just returning a bool whether there was a hit or not. If you wanted some different behavior you can implement your own collector. For these common use cases you can just use the handy wrapper functions instead of dealing with the collector directly.

For example if your use case just wants to know the number of hits then you don't need to write them to an array first, you can just write a collector which increments a counter instead of writing to a NativeList.

Got it! Thanks, Rory!