- Home /
Question by
Jorrit2002 · Feb 23, 2020 at 10:28 PM ·
componentmouseclickselection
MouseButtonDown stops working after removing an component and raycast missing an target
I started learning unity and I've made some selecting system using ECS. The system adds an SelectedComponent to an entity when the raycast hits an object (player or enemy sphere). When selecting the other object, the component is removed and added to the newly selected object. This all works fine until the raycast misses an object. The SelectedComponent is removed from all entities but the Input.GetMouseButtonDown(0) stops working (only in this system). This only occurs when the SelectedComponent is removed. When I comment this part of the script:
entityManager.RemoveComponent<SelectedComponent>(oldTarget))
the Input.GetMouseButtonDown("0") works fine after missing an target.
I don't understand this strange behaviour.. could someone explain why this is happening?
using UnityEngine;
using Unity.Entities;
using Unity.Physics;
using Unity.Rendering;
using Unity.Physics.Systems;
using Unity.Transforms;
public class SelectingSystem : ComponentSystem
{
PhysicsWorld physicsWorld => World.DefaultGameObjectInjectionWorld.GetExistingSystem<BuildPhysicsWorld>().PhysicsWorld;
EntityManager entityManager => World.DefaultGameObjectInjectionWorld.EntityManager;
protected override void OnUpdate()
{
if (Input.GetMouseButtonDown(0))
{
DeselectTarget();
GetInteractableObjects();
}
}
private void DeselectTarget()
{
// deselects current target so there is only one entity with SelectedComponent
EntityQuery selectedQuery = GetEntityQuery(ComponentType.ReadWrite<SelectedComponent>());
if (selectedQuery.CalculateEntityCount() == 1)
{
Entity oldTarget = selectedQuery.GetSingletonEntity();
entityManager.RemoveComponent<SelectedComponent>(oldTarget);
}
}
private void GetInteractableObjects()
{
var screenPointToRay = Camera.main.ScreenPointToRay(Input.mousePosition);
var rayInput = new RaycastInput
{
Start = screenPointToRay.origin,
End = screenPointToRay.GetPoint(1000),
Filter = CollisionFilter.Default
};
if (physicsWorld.CastRay(rayInput, out Unity.Physics.RaycastHit hit))
{
Entity selectedEntity = physicsWorld.Bodies[hit.RigidBodyIndex].Entity;
if (entityManager.HasComponent<InteractableComponent>(selectedEntity))
{
RenderMesh renderMesh = entityManager.GetSharedComponentData<RenderMesh>(selectedEntity);
var mat = new UnityEngine.Material(renderMesh.material);
mat.SetColor("_Color", Random.ColorHSV());
renderMesh.material = mat;
Translation translation = EntityManager.GetComponentData<Translation>(selectedEntity);
entityManager.SetSharedComponentData(selectedEntity, renderMesh);
entityManager.AddComponentData(selectedEntity, new SelectedComponent { });
entityManager.AddSharedComponentData(selectedEntity, new PositionSharedComponent { position = translation.Value });
}
}
}
}
Comment