Using a raycast to get transform on specific layer

I’m building a simple drag and drop inventory using 2 type of cubes: Dragables and Slots. I want to get a reference of the Slot when I let go of a Dragable on top of it. This is the code that I can’t get to work properly:

RaycastHit hitInfo = new RaycastHit();
bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo, 1 << LayerMask.NameToLayer("Slots"));
if (hit) 
{
	Debug.Log(hitInfo.collider.name);
}

The layer mask doesn’t seem to be working because it returns the first collider on all layers (in this case the Dragable) instead of only triggering on the Slots.

Here is my work around, which works great, but it seems like I shouldn’t need this much code?

RaycastHit[] hits;

hits = Physics.RaycastAll(Camera.main.ScreenPointToRay(Input.mousePosition));
int i = 0;
while (i < hits.Length) {
	RaycastHit hit = hits*;*
  • if( hit.collider.tag == “Slot” ){*
  •  inSlot = true;*
    
  •  Slot = hit.collider.transform;*
    
  •  transform.position = new Vector3(hit.collider.transform.position.x, hit.collider.transform.position.y, -5f);*
    
  •  return;*
    
  • }*
  • i++;*
    }

There is no form of Raycast() that takes a mask as the third parameter. This Raycast() is using the value you are passing for a mask as the distance parameter. Add a distance parameter and your Raycast() should work:

bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo, Mathf.Infinity, 1 << LayerMask.NameToLayer("Slots"));

Note you don’t have to do ‘new RaycastHit()’. RaycastHit is a struct not a class.

Send a raycast from the Dragable downwards. I don’t think raycasts can send rays through colliders to hit a collider on the other side.

This might be new for Unity 5, but sounds like it should be possible to specify a layer mask, like you suggest:

In fact, here are some examples as well: