Updating a nativearray (to avoid doing ToComponentDataArray multiple times)?

Since the new version of the entities package I’m running into a issues, slowly solving them one by one. But I have question I wonder how I should solve.

I have a custom physics engine, and to check one object with another I do the following (simplified)

var physicsArray = _group.ToComponentDataArray<Physics>(Allocator.Persistent);

for(var step = 0; step < 10; step++)
{
Entities.ForEach((ref Physics p1) => {
    for(var i = 0; i < physicsArray.length; i++)
    {
        var p2 = physicsArray[i];

        // do collision detection and correction with p2

        // update p1 with the sum of the corrections
    }
});

// I scheduled each step-job after the other, so one is dependent on the other
}

This all works well, but as I’m running this ForEach multiple times (10 physics steps per tick) I’d like to keep physicsArray also updated with the modified physics objects. Before I had this approach where I had two physics arrays, read from one and wrote to the other that was bit hacky but worked. Ideally I could update it without querying it every step.

What would be the right approach?

The right approach is to use Allocator.TempJob instead of Allocator.Persistent and keep doing that ToComponentDataArray every OnUpdate. ToComponentDataArray has an async version too in case you are worried about the time it might take.

Thanks for the answer. The reason I wonder about it is as I’m doing it 10 times per OnUpdate (well a manually called FixedUpdate), because of how the physics engine work, so I was wondering that maybe there’s some way updating it, although might be premature optimizations. Maybe I’ll do some profiling!

You can use ToEntityArrayAsync to get entities with Physics component, then use multiple ComponentDataFromEntity to read the components (so you need to only allocate one array)

If you want to avoid allocating array completely you can use ArchetypeChunk, this post has an example: Looping over two separate entity types

Furthermore you could implement space partitioning using NativeMultiHashMap for your physics engine, currently it looks like you are checking each entity vs other entity which could scale pretty bad. There is an old tutorial about this in 2d maybe it could give you some ideas

, but uses some deprecated code

Oh cool! Thanks I’ll out that video! I actually do have space partitioning, it’s handled by sorting the entities array, and then I have two other arrays (a start and a stop index). So I get the start and stop index for a tile (this being tile based) and then just check the entities in the entity array between those indices, I think this works well enough, it’s not optimal but seems to work alright with unity’s ECS. I guess once you learn all the features of ECS you’ll have more tricks but now it does feel like I do my best with very few tools, so I kinda need to trick unity into doing what I want =)