Detect mouse clicked on GUI

后端 未结 3 1709
北海茫月
北海茫月 2021-01-15 05:19

I got a problem in my project. I want to know that mouse cliked happend on GUI or on any game object. I have tried this but it is showing null reference exception

         


        
相关标签:
3条回答
  • 2021-01-15 05:57

    There is some approaches that you can use to detect if your mouse is over a legacy GUI element here I'll show you one that I hope will work fine for you, if not research a little about "mouse over GUI" and you'll find a lot of different ways to do it (this one is what I use on my legacy GUI projects and usually works fine with touch):

    Create an easily accessible behaviour (usually a singleton) to hold your MouseOverGUI "status":

    if you are using GUILayout.Button you need to catch the last drawn rect, if you are GUI.Button just use the same rect you passed as button's param like this:

    // 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;
         }
    }
    

    after that you just need to test if your mouseOverGUI is true or false to allow or not your desired click actions before execute them. (a good understanding of unity loops will help you to catch and test the flag in correct timing to avoid problems expecting to get something that already changed)

    edited: also remember to reset mouseOverGUI to false when it is not over GUI ;)

    0 讨论(0)
  • 2021-01-15 06:12

    IsPointerOverGameObject() is fairly broken on mobile and some corner cases. We rolled our own for our project and it works like a champ on all platforms we've thrown it at.

    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;
    }
    

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

    0 讨论(0)
  • 2021-01-15 06:12

    Finally got my answer here: There are three ways to do this, as demonstrated in this video tutorial. this video save me:).

    1. Use EventSystem.current.IsPointerOverGameObject

    2. Convert your OnMouseXXX and Raycasts to an EventSystem trigger. Use a physics raycaster on the camera

    Implement the various handler interfaces from the EventSystems namespace. Use a physics raycaster on the camera.

    0 讨论(0)
提交回复
热议问题