I am trying to determine what object I am clicking with the help of a raycast, however it doesn't always work
In update I call:
if (Input.GetMouseButtonDown(0))
{
selectedObject = null;
selectedUnits = new List<Unit>();
Select(Input.mousePosition);
startPos = Input.mousePosition;
}
which calls:
void Select(Vector2 screenPos)
{
Ray ray = cam.ScreenPointToRay(screenPos);
RaycastHit hit;
//Debug.Log("1");
if (Physics.Raycast(ray, out hit, 100))
{
OnClicked(hit.transform.tag);
//Debug.Log("2");
if (hit.transform.GetComponent<Unit>())
{
//Debug.Log("3");
if (!selectedUnits.Contains(hit.transform.GetComponent<Unit>()))
{
//Debug.Log("4");
selectedUnits.Add(hit.transform.GetComponent<Unit>());
}
}
if (hit.transform.GetComponent<Building>())
{
if (hit.transform.GetComponent<Building>() != selectedObject)
{
selectedObject = hit.transform.gameObject;
}
}
}
}
Detecting a "building" always works and is fine, but clicking on a "unit" works anywhere between 0 and 5 times per play session before it returns nothing anymore like the object doesn't exist. I have tried to find where it gets stuck and it gets stuck after the 2nd debug (debug 1 and 2 print but 3 and 4 do not).
This is the Unit in the inspector
and this is it in the hierarchy
When drawing the ray here you can see it hits the cube 3 times before it just passes right through the 4th time.
it seems like after each hit the ray penetrates the collider more and more
But how and why can it only hit it a couple of times before it passes through. After a certain amount of clicks with or without moving my mouse it just doesn't hit it anymore even though in the inspector nothing changes and there are no scripts that alter the box collider.
I hope someone knows what's going wrong, thanks!
isTrigger
flag, or changing the unit's transform scale (especially anything that could make the scale 0 or negative along an axis)? \$\endgroup\$ – DMGregory♦ Jan 4 at 22:12