'In Unity3d How detect touch on UI or not?
In make Unity3d mobile application. And I have a problem: How detect touch on UI or not?
I try this (but now work)
UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()
and this
private static List<RaycastResult> tempRaycastResults = new List<RaycastResult>();
public bool PointIsOverUI(float x, float y)
{
var eventDataCurrentPosition = new PointerEventData(EventSystem.current);
eventDataCurrentPosition.position = new Vector2(x, y);
tempRaycastResults.Clear();
EventSystem.current.RaycastAll(eventDataCurrentPosition, tempRaycastResults);
return tempRaycastResults.Count > 0;
}
Solution 1:[1]
Please try this :
// for Android check differently :
if(EventSystem.current.IsPointerOverGameObject(0) return false;
// for windows check as usual :
if (EventSystem.current.IsPointerOverGameObject())
return false;
Solution 2:[2]
Add this to the clickable object
private MyUIHoverListener uiListener;
private Vector3 mousePos;
private void OnMouseDown()
{
mousePos = Input.mousePosition;
Debug.Log(Input.mousePosition);
}
private void OnMouseUp()
{
//this part helps to not trigger object when dragging
mousePos -= Input.mousePosition;
//Debug.Log(mousePos);
if(mousePos.x < 3 && mousePos.y < 3 && mousePos.z < 3 && mousePos.x > -3 &&
mousePos.y > -3 && mousePos.z > -3)
{
//Debug.Log("NOT MOVED");
if (!GameMan.ObjectClickBlocker)
{
if (uiListener.IsUIOverride)
{
// Debug.Log("Cancelled OnMouseDown! A UI element has override this object!");
}
else
{
// Debug.Log("Object OnMouseDown");
StartCoroutine(LoadThisBuilding( 0));
ToggleBuildingMenu();
}
}
}
}
Add this on the object in front of the clickable object:
public class MyUIHoverListener : MonoBehaviour
{
[SerializeField]
public bool IsUIOverride { get; private set; }
void Update()
{
// It will turn true if hovering any UI Elements
IsUIOverride = EventSystem.current.IsPointerOverGameObject();
}
void OnDisable()
{
IsUIOverride = false;}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Amirhossein Yari |
| Solution 2 | 2winners |
