Interact with uGUI button using code?

Hello,

I’m having trouble trying to interact with uGUI buttons using code. My goal is to simulate the usual behaviour of the standard button, changing from “normal color”, to “highlighted color”, to “pressed color” but using code instead of touch or a mouse.

Right now my standard button I have a method that detects when a “cursor” GameObject (Not attached to the mouse or touch position) is inside the boundaries of the button. I’d like that when it’s detected that the gameobject is inside the boundaries the animation from “normal” to “highlighted” plays as if the mouse cursor was over the button.

Similarly I want to invoke the “onClick” event as if I clicked or touched the button, but using code.

I was expecting some method like button.isHighlighted(true) and button.isClicked(true) so I could manually change the appearence and ultimately interact with the button.

Is there any way I can achieve this?

If it helps, picture the following situation: An AI cursor in a tutorial shows up and “hovers” above the UI button and then “press” it launching the usual OnClick behavior defined in the inspector.

Thanks in advance,
Sergio

You’re looking for OnSomething public functions of button (e.g. OnPointerDown, OnPointerEnter, etc.). HERE is one of my answers that will show you how to implement them in code. Attach that code to your button as component and do what you expect on specific event.

P.S. Check this answer as well, just to keep that in mind.

P.P.S. An update to answer your updated question:

So you want to simulate inputs on your button. In order to do that you can use EventSystems.ExecuteEvents.Execute. I’ll show you an example how to use that:

 ExecuteEvents.Execute(yourButton.gameObject, new PointerEventData(EventSystem.current), ExecuteEvents.pointerEnterHandler); // that will trigger OnPointerEnter event.