Unity DOTS Systems - Method Extraction within Entities.ForEach?

I tried to refactor the code inside the Entities.ForEach using method extracting. E.g. MoveToDestination (see image). This caused the entities to stop moving, even though it was actually the exact same code. Why is that? What are good practices to keep code clean/readable in this part?

public class MoverToDestinationSystem : SystemBase
{
    protected override void OnUpdate()
    {
        float deltaTime = Time.DeltaTime;

        Entities.ForEach((ref Translation translation, ref Rotation rotation, in Destination destination, in MovementSpeed speed) =>
        {
            if (ReachedDestination(translation, destination)) { return; }
            float3 toDestinationDirection = destination.Value - translation.Value;
            rotation.Value = quaternion.LookRotation(toDestinationDirection, new float3(0, 1, 0));
            float3 movementToDestination = math.normalize(toDestinationDirection) * speed.Value * deltaTime;
            MoveToDestination(translation, destination, toDestinationDirection, movementToDestination);

        }).ScheduleParallel();
    }

    private static void MoveToDestination(Translation translation, in Destination destination, float3 toDestinationDirection, float3 movementToDestination)
    {
        if (math.length(movementToDestination) >= math.length(toDestinationDirection))
        {
            translation.Value = destination.Value;
        }
        else
        {
            translation.Value += movementToDestination;
        }
    }

    private static bool ReachedDestination(Translation translation, Destination destination)
    {
        return math.all(destination.Value == translation.Value);
    }

    private static void FaceDestination(Rotation rotation, float3 toDestination)
    {
        rotation.Value = quaternion.LookRotation(toDestination, new float3(0, 1, 0));
    }
}

[image]

Ouch, my poor eyes! Please just paste in code for future questions (format them by typing ``` (three backward apostrophes on a line by itself) before and after the code. Then it’ll be much easier to read than a screen shot (and respect light/dark preferences).

My best guess on this is that you’re passing the Translation to moveToDestination without the ref keyword. This means that a copy of the struct is being made instead of a pointer to the struct itself.

1 Like

Thanks you are right! It was just the missing ref modifiers.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms