# Unity raycasting not always detecting component

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

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!

• Can you show us how the hierarchy of your unit is set up, including what components exist on each object in the hierarchy? – DMGregory Jan 4 at 21:36
• Does anything modify the collider on the unit at runtime - such as by changing its size or offset, isTrigger flag, or changing the unit's transform scale (especially anything that could make the scale 0 or negative along an axis)? – DMGregory Jan 4 at 22:12
• @DMGregory there is no script that contains any code that modifies anything in regards to the mentioned properties of the cube – Bosanac95 Jan 5 at 14:14

The most likely problem is that you're hitting something else for whatever reason. You say that your debug log "2" is always going off. Instead of logging "2", try logging hit.transform.name instead. This would tell you what it is you're hitting. Then you'd have a much easier job of figuring out what's going wrong.
You can also use Debug.DrawRay to make sure the ray is being cast as you expect it to. (This is best used in a "split screen" mode with both the Game view and the Scene view open side by side.)
• Then try using Debug.DrawRay and checking to see that the ray is being cast the way you expect. – Mason Wheeler Jan 4 at 21:58