UGUI判断鼠标或者手指是否点击在UI上

以下方法适合在Editor下使用,在移动端无效(转自雨松)

void Update ( ) {
if ( Input . GetMouseButtonDown ( 0 ) )
{
Debug . Log ( EventSystem . current . gameObject . name ) ;
if ( EventSystem . current . IsPointerOverGameObject ( ) )
Debug . Log ( "当前触摸在UI上" ) ;
else Debug . Log ( "当前没有触摸在UI上" ) ;
}
}
在移动端无效的原因是: IsPointerOverGameObject()在editor下默认传入pointID为-1,在移动端需要传入具体fingerid值
因此在移动端可以考虑以下方法:

void Update ()
{
               if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began) {
                        if (IsPointerOverGameObject (Input.GetTouch (0).fingerId)) {
                                Debug.Log("当前触摸在UI上");
                        } else {
                                Debug.Log("当前没有触摸在UI上");
                        }
               }        
}
 
bool IsPointerOverGameObject( int fingerId )
{
    EventSystem eventSystem = EventSystem.current;
    return ( eventSystem.IsPointerOverGameObject( fingerId )
        && eventSystem.currentSelectedGameObject != null );
}

当然也可以使用射线的原理来判断(无论移动端还是window下都可使用)需要传入的参数为画布和屏幕点击位置

///


/// Cast a ray to test if screenPosition is over any UI object in canvas. This is a replacement
/// for IsPointerOverGameObject() which does not work on Android in 4.6.0f3
///

private bool IsPointerOverUIObject(Canvas canvas, Vector2 screenPosition) {
    // Referencing this code for GraphicRaycaster https://gist.github.com/stramit/ead7ca1f432f3c0f181f
    // the ray cast appears to require only eventData.position.
    PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
    eventDataCurrentPosition.position = screenPosition;
 
    GraphicRaycaster uiRaycaster = canvas.gameObject.GetComponent();
    List results = new List();
    uiRaycaster.Raycast(eventDataCurrentPosition, results);
    return results.Count > 0;
}

你可能感兴趣的:(UGUI,Unity3d)