Utilities & Extensions

DOTSNET comes with a few usability extensions for ECS, found in Extensions.cs:

Entity.UniqueId()

On the server we need to store spawned entities by their unique ids.

We added a simple Entity.UniqueId() extension for that. The id is created from the two Entity struct fields: Index & Version, and is guaranteed to be unique as long as the program runs.

DynamicBuffer.Contains(value)

DynamicBuffer doesn’t come with a Contains helper function, and adding one can be cumbersome since there are a few things to consider for Burst support, so DOTSNET comes with one to make life easier.

Note that while it’s not necessary, for maximum performance it’s recommended to implement GetHashCode() in your IBufferElementData structs so that DynamicBuffer.Contains doesn’t default to using Reflection for GetHashCode.

NativeMultiMap.TryIterate(key, out value, ref iterator)

Iterating a NativeMultiMap is cumbersome because we need to call both TryGetFirstValue and TryGetNextValue:

if (messages.TryGetFirstValue(connectionId, out message,
    out NativeMultiHashMapIterator<int> it))
{
    Send(message, connectionId);
    while (messages.TryGetNextValue(out message, ref it))
    {
        Send(message, connectionId);
    }
}

The problem with this syntax is that it requires redundant follow-up code. Notice how Send() needs to be in there twice.

Instead, DOTSNET provides a TryIterate helper function:

NativeMultiHashMapIterator<T>? iterator = default;
while (messages.TryIterate(connectionId, out message, ref iterator))
{
    Send(message, connectionId);
}

This way we don’t need redundant follow-up code. Send is only called once.

Note: don’t forget the “?” when declaring your iterator type.

Last updated