Pass on data

How do I actually pass data to the commands that I issue to my entities?

Clojure

Look, we have an intruder here! It's time to send our army there to eliminate the threat. But how do we even do that?

The easiest way is to transfer the value directly to the query. This is called Clojure. It is simple, but not particularly efficient. For most purposes, however, it will suffice.

Allocates the passed value on the heap with each call. Produces garbage that could be avoided.

Alternatively, you can cache the static value, which avoids the allocation. This is not possible everywhere, but where it works, it works wonderfully.

And already all our entities are moving in the direction of the intruder, brilliant... right?

Inline query

Another way is to pass on the values using a Struct. For this we can use the InlineQuery and the IForEach interface.

private struct VelocityUpdate: IForEach<Position, Velocity>
{
    public Position IntruderPosition;
    
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public void Update(ref Position pos, ref Velocity vel)
    {
        MoveTowards(ref pos, ref vel, IntruderPosition);
    }
}

var velUpdate = new VelocityUpdate{ IntruderPosition = DetectIntruder(); };
World.InlineQuery<VelocityUpdate, Position, Velocity>(in queryDesc, ref velUpdate);

The struct prevents the value from being associated. This method is fast and efficient, produces no garbage!

Now our entities are also moving in the direction of the intruder... but more efficiently. Especially good if we have a lot of entities. It's also quite nice, isn't it? But there is another variant.

Custom loop

That's not enough for you? Well, then we have one last ace up our sleeve. Drink this potion, it will enable you to write queries yourself!

You can now iterate archetypes and chunks yourself, which removes any abstraction. This in turn allows you to pass values and logic however you want.

Fast and efficient. It doesn't really get more efficient than that! It's more boilerplate code, but it's really useful here and there. By the way, if that's not enough for you, have you looked at the source generators?

And now you can move even more entities efficiently, perhaps even hundreds of thousands? Or even millions? Who knows, time to let them march!

Last updated