0

I'm needing to have some funcitonality ignored, if I have happen to touch my UI. However, I am struggling to detect if I am actually touching it or not.

My UI makes use of the native UI inside Unity. My thought behind it was to simply check the layers and if I touched anything on that layer, I'd stop any functionality from happening.

So I wrote this to test it:

    void Update () {
    if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began) 
    {
        Ray ray = Camera.main.ScreenPointToRay( Input.GetTouch(0).position );
        RaycastHit hit;

        if ( Physics.Raycast(ray, out hit,  Mathf.Infinity, mask))
        {
            Debug.Log("hit ui");
        }
    }
}

However, when I press the button on my UI (it's comprised of a Canvas, Panel and a single button to test), nothing happens. However, if I place a cube in the scene and assign that to the UI layer, the debug log appears.

Why is that?

N0xus
  • 2,674
  • 12
  • 65
  • 126
  • http://answers.unity3d.com/answers/885196/view.html – Fattie Feb 15 '16 at 17:27
  • Possible duplicate of [How to make gameplay ignore clicks on UI Button in Unity3D?](http://stackoverflow.com/questions/35529940/how-to-make-gameplay-ignore-clicks-on-ui-button-in-unity3d) – Fattie Feb 26 '16 at 04:32

2 Answers2

1

I guess the key here is: EventSystems.EventSystem.current.IsPointerOverGameObject()

It should return true whether you are hovering UI. Try implementing it like this:

using UnityEngine.EventSystems;
...
if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began) 
{
    if(EventSystems.EventSystem.current.IsPointerOverGameObject()) {
          Debug.Log("UI hit!");
    }
}
Rafal Wiliński
  • 2,240
  • 1
  • 21
  • 26
1

For a 2d elements you need to use Physics.Raycast2d instead of Physics.Raycast and make sure that your UI element have a Collider2D

RaycastHit2D hit = Physics2D.Raycast(worldPoint,Vector2.zero);

        //If something was hit, the RaycastHit2D.collider will not be null.
        if ( hit.collider != null )
        {
            Debug.Log( hit.collider.name );
        }
joreldraw
  • 1,736
  • 1
  • 14
  • 28
  • Full detailed and tedious answer for modern Unity ... http://answers.unity3d.com/answers/885196/view.html – Fattie Feb 15 '16 at 17:27