0

How do I stop a RayCast from going through a UI Button and hitting the collider behind the button?

Some things I tried:

  • The collider covers the entire view, but it is located on (0,0,2)
  • The button is on (0,0,-5), so in front of the collider from the camera's point of view.
  • I noticed a Graphic Raycaster component on the Canvas and I set that to Blocking Objects: All, Blocking Mask: Everything, and Ignore Reverse Graphics: True (true by default)

So every time I click the button, it executes the event, but my player ends up behind the button, because the RayCast also hit the other collider, behind the button.

void Start(){
    touchControl = LayerMask.GetMask("TouchControl");
}

// Update is called once per frame
void Update () {

    if (Input.GetMouseButton(0))
    {
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit, 100, touchControl))
        {
            Destroy(GameObject.FindGameObjectWithTag("Destination"));
            CalculatedDestination = Instantiate(Destination, hit.point, Quaternion.identity);
        }
    }}
Fabio S.
  • 460
  • 7
  • 22
  • What's the raycast used for? – Programmer Jan 13 '18 at 00:53
  • @Programmer I updated the question with a snippet of code using the Raycast. – Fabio S. Jan 13 '18 at 00:55
  • That doesn't answer the question in my first comment, I need to know what you use that raycast code for so that I can make up an answer that prevents this from happening. It looks like you use it to detect click on your 3d model? Is right right? – Programmer Jan 13 '18 at 00:57
  • @Programmer Yes. With the mouse click, I use it to detect a point in the 3D world, so I can move the player there. – Fabio S. Jan 13 '18 at 00:59
  • 3
    Use `EventSystem.current.IsPointerOverGameObject` to do that. See duplicate for full example on both mobile and desktop. Let me know if there is problem.... – Programmer Jan 13 '18 at 01:02
  • 2
    @Programmer I see it. Thank you pointing me in the right direction! This does the trick. if (Input.GetMouseButton(0) && !EventSystem.current.IsPointerOverGameObject()) { ... } – Fabio S. Jan 13 '18 at 01:04
  • 1
    You are welcome! Remember to handle on mobile device like I did with `EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId)` otherwise you may run into issues – Programmer Jan 13 '18 at 01:09

0 Answers0