簡體   English   中英

檢測鼠標在GUI上的點擊

[英]Detect mouse clicked on GUI

我的項目有問題。 我想知道鼠標點贊發生在GUI或任何游戲對象上。 我已經嘗試過了,但是顯示空引用異常

EventSystem eventSystem = EventSystem.current;
            if (eventSystem.IsPointerOverGameObject())
               Debug.Log("left click over a gui element");

如何檢測? 有沒有可用的活動?

IsPointerOverGameObject()在移動設備和某些IsPointerOverGameObject()情況下相當IsPointerOverGameObject() 我們為項目投入了自己的精力,在我們投入的所有平台上,它都像冠軍一樣工作。

private bool IsPointerOverUIObject() {
  PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
  eventDataCurrentPosition.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
  List<RaycastResult> results = new List<RaycastResult>();
  EventSystem.current.RaycastAll(eventDataCurrentPosition, results);
  return results.Count > 0;
}

來源: http : //forum.unity3d.com/threads/ispointerovereventsystemobject-always-returns-false-on-mobile.265372/

您可以使用一些方法來檢測鼠標是否在舊版GUI元素上,如果您不對“在GUI上進行鼠標”有所研究,那么我將向您展示一種方法,希望對您有用。找到許多不同的方法來做到這一點(這是我在舊版GUI項目上使用的方法,通常在觸摸下可以正常工作):

創建一個易於訪問的行為(通常為單例)以保持MouseOverGUI的“狀態”:

如果您使用的是GUILayout.Button,則需要捕獲最后繪制的矩形,如果您使用的是GUI.Button,則只需使用與作為按鈕的參數傳遞的矩形相同的矩形:

// GUILayout
( Event.current.type == EventType.Repaint &&
    GUILayoutUtility.GetLastRect().Contains( Event.current.mousePosition ) ) {
        mouseOverGUI = true;
     }
} // you need call it in your OnGUI right after the call to the element that you want to control

// GUI
( Event.current.isMouse &&
    yourRect.Contains( Event.current.mousePosition ) ) {
        mouseOverGUI = true;
     }
}

之后,您只需要測試mouseOverGUI是true還是false,就可以在執行它們之前允許您想要的單擊動作。 (對統一循環的深入了解將有助於您以正確的時機捕獲和測試該標志,以避免出現預期已發生變化的問題)

編輯:還記得在未通過GUI時將mouseOverGUI重置為false;)

終於在這里得到了我的答案:如本視頻教程所示,有三種方法可以做到這一點。 這部影片救了我:)。

  1. 使用EventSystem.current.IsPointerOverGameObject

  2. 將您的OnMouseXXX和Raycasts轉換為EventSystem觸發器。 在相機上使用物理光線投射器

從EventSystems命名空間實現各種處理程序接口。 在相機上使用物理光線投射器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM