Search Unity

Click and change state of button using code?

Discussion in 'UGUI & TextMesh Pro' started by SVC-Games, Apr 23, 2015.

  1. SVC-Games

    SVC-Games

    Joined:
    May 21, 2013
    Posts:
    137
    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
     
  2. SimonDarksideJ

    SimonDarksideJ

    Joined:
    Jul 3, 2012
    Posts:
    1,689
    The best option is to built your own input module to raise the input events using whatever input paradigm you are creating. You can see the existing input modules and how they work here:
    https://bitbucket.org/Unity-Technol...ityEngine.UI/EventSystem/InputModules/?at=4.6

    There isn't a way "currently" to directly interact with a Button component (actually the Selectable component in your case) to update it's state programatically, it all currently depends on the events.