Best practice to know when we press a button or not

Actual performance of my game is the following:

When we press left button of our mouse on a point of our world our character goes to that point. I detect the point with Input.mousePosition within OnGUI()

There are several buttons at the bottom of the screen. They belong to a canvas object with value “overlay” on render mode.

I don’t want move the character when one button at the bottom is clicked, so I figure out if the click has happened in a button with EventSystem.current.IsPointerOverGameObject()

Is the best practice?

Yes, you can use that for avoiding clicking to world when over the UI.

And probably no need to use OnGUI() for that movement, just use Update()

I have tried putting all my OnGui() code within the update() and I get a runtime error “nullReferenceException” in the line where I declare:

Event e = Event.current;

My code is:

        Event e = Event.current;
        if (e.button == 0 && e.type == EventType.MouseDown &&(!EventSystem.current.IsPointerOverGameObject())) {
//do the movement to Input.mousePosition
}

It seems Event,current isn’t initialized in update(). I also read that UI events should be managed within OnGui(). How can I fix my code to catch the click within update()? doing it in update is more performance?

I’m thinking other alternative: I could manage the left mouse click using a “event trigger” of type “Pointer click” I’m very interesting in the performance of the app, so which alternative is the most efficient?

You are messing up UI and GUI. The systems are totally different and don’t work well together.

Legacy GUI works by receiving events in OnGUI.

UI works by the EventSystem triggering methods inside of your code.

1 Like