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);
}
}