How can I raycast gameobjects with specific layer ?
Hi everyone, I want to raycast gameobject that have "UI" layer. Currently, the official documentation seems to be clear about how I can do this. But, it just doesn't work. Here is my actual code :
// Use this for initialization
void Start ()
{
this.m_layer_ground = LayerMask.NameToLayer("UI");
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButton(0))
{
print("Press Mouse Left Button");
RaycastHit hit = new RaycastHit();
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 1000f, this.m_layer_ground))
{
print("Touch UI");
}
}
}
So, on Start function I get the good layer mask. Then, on Update function I wait for a mouse button held down. Then I create a ray from camera through screen point and finally I test if the ray collide a gameobject with "UI" layer with Physics.Raycast. I have several gameobject that have a "UI" layer on my scene and there are a box collider that cover there surface. But, when I click on one of these gameobject, I don't have any "Touch UI" on Unity console.
I don't see the problem...
Answer by hexagonius · Feb 24, 2016 at 08:43 AM
UI Elements use a graphics raycaster to be targeted. this component is what you would need
http://docs.unity3d.com/ScriptReference/UI.GraphicRaycaster.html
It works in conjunction with an EventSystem and is quite easy to use. create an event system and hook a function into the OnClick event of your UI element.if it does not have one add a EventTrigger component and create that first
Your answer
Follow this Question
Related Questions
Get Name of UI gameobject with raycast 3 Answers
Offset between mouse cursor position and "hit" position with worldspace UI's 1 Answer
Unity 5 UI not blocking Raycast Collider ( Physics Raycast ) 1 Answer
NullReference in Eventsystem Raycast eventCamera 0 Answers
Survival shooter enemy not taking damage 0 Answers