Selecting script not working when containing ForEach

For a 3d game, I am trying to create a select system based on raycast from camera to mouse position. If it returns an Entity, then a tag is added to the entity. However to remove old tags, I run a foreach loop to remove them, however it stops the script from functioning with no errors. I do find it weird as I have seen multiple similar examples of such scripts.

As a side note, does anyone have a recommendation on how to create such a system in a better way

    protected override void OnUpdate()
    {
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {           
            float3 cameraPosition = MonoToEntityManager.instance.CameraPosition();
            Camera cameraComponent = MonoToEntityManager.instance.cameraComponent;

            float3 rayDirection = cameraComponent.ScreenPointToRay(Input.mousePosition).direction;

            Entity rayHitEntity = Raycast(cameraPosition, rayDirection * 50f);

            if (rayHitEntity == Entity.Null)
            {
                Debug.DrawRay(cameraPosition, rayDirection * 50f, Color.red, 10f);
                return;
            }

            Entities.WithAll<Tag_SelectedEntity>().ForEach((Entity entity) =>
            {
                EntityManager.RemoveComponent<Tag_SelectedEntity>(entity);
            }).WithoutBurst().Run();

            EntityManager.AddComponent<Tag_SelectedEntity>(rayHitEntity);

            Debug.DrawRay(cameraPosition, rayDirection * 50f, Color.green, 10f);
        }
    }

Why not store the latest “selected” entity and just remove it the moment you hit something different? This way you dont need to have such a foreach loop

That’s true, this is one way to fix it. I am however unsure why my code still does not work. Do you have any ideas?

The whole script seems to be working when an Entity with the correct tag exists. However when removed, the whole script stops working. Is there a way around this?

Instead of WithoutBurst(), use WithStructuralChanges().

[AlwaysUpdateSystem] on system.
ILPP will interpret your code as a different thing which also will create EntityQuery for the system, which in turn decide - should run system or not. If you haven’t entities which match EntityQuery - the system wouldn’t run, this is how it works by design.

Thanks, now it is working.

Hidden wizardry…

How are you supposed to know that? Is it in the documentation somewhere?

https://docs.unity3d.com/Packages/com.unity.entities@0.11/api/Unity.Entities.SystemBase.html under Entity queries