- Home /
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[i];
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++;
}
Answer by robertbu · Feb 02, 2014 at 08:37 PM
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.
Answer by highpockets · Feb 02, 2014 at 08:29 PM
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.
Hmm, I was under the impression that if you specify a layer mask, the raycast would ignore all colliders not on that layer ('Slots' in my example), but perhaps I'm not clear on how layer masks work. I'll give your idea a try, thanks.
Answer by svendkiloo · May 03, 2016 at 09:38 AM
This might be new for Unity 5, but sounds like it should be possible to specify a layer mask, like you suggest:
http://docs.unity3d.com/ScriptReference/Physics.Raycast.html
In fact, here are some examples as well:
Your answer

Follow this Question
Related Questions
RaycastHit returns object without collider, in wrong layer 1 Answer
Raycast should ignore everything but player, yet still gets interrupted 1 Answer
BoxCollider2D is not working as expected 1 Answer
Is it possible to allow a raycast to pass through a collider to hit things behind it? 6 Answers
How to create User layer that acts like the "Ignore Raycast" layer? 1 Answer