Using Event.current.mousePosition within OnGUI


I’m having a bit of trouble with this.
I am using if Event.current.mousePosition to detect if the user clicks my gui elements.

When I place this in OnGUI(), everything inside my if statement gets executed twice. I understand this is because OnGUI() is executed twice per frame.

When I move the if statement to Update(), I get null pointer errors, which I understand are because I need to use Input.mousePosition when inside the Update() method.

However, Input.mousePosition does not work, which I believe is because it is based on different coordinates or something?

How can I solve this?


You have to understand what OnGUI actually is. It is the event callback. It is called for various events. The two events Layout and Repaint are invoked every frame, but there are a lot more event types. You have to check Event.current.type even before you use anything else from the Event class. Not all events have all event parameters.

Try using a Vector2 for the mouse position, and define it in Update().

Vector2 mouse;
Rect yourRectangle;

void Update()
    mouse = new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y);
        print("Rect contains mouse Position!");