- Home /
Why Raycast hit a layer that I have removed from mask?
It sounds a bit strange but I made a mask which is `~LayerMask.NameToLayer("Tower")` which should "hit" everything except that layer:
Ray ray = Camera.mainCamera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
bool raycastResult = Physics.Raycast(ray, out hit, Mathf.Infinity, ~LayerMask.NameToLayer("Tower"));
if (raycastResult)
Debug.Log("Layer: " + LayerMask.LayerToName(hit.transform.gameObject.layer));
However, Debug.Log outputs: "Layer: Tower". Am I doing something wrong?
I tried by reverting the layermask, and obviusly I can't hit anything (except towers which are not placed). The layer is correctly set on the tower.
Is it a bug maybe?
Edit 1: I still can't find a solution, are there any possibility that there is a "hidden" layer added to my prefab?
Answer by Bunny83 · Dec 04, 2012 at 06:21 PM
According to LayerMask.NameToLayer it does return the layer index and not it's layermask. So use it like this:
~(1<<LayerMask.NameToLayer("Tower"))
You just can test it by Debug.Log what ever the function returns. This would be the first thing i would check ;)
Oh man, if that's the problem I wasted an entire day.
Well, I admit that those two static functions are badly placed. They actually have nothing to do with the Layer$$anonymous$$ask itself. The Layer$$anonymous$$ask class is just a wrapper for an integer value. The class itself does no conversion at all. The only advantage is that Unity will display the Layermask dropdown in the inspector when you use this type on a public variable.
The Layername-to-index and index-to-layername works with the layer index which is stored in the layer property of a GameObject.
Seems you are right, thanks a lot. Still I wasted 1 day <.<