Search Unity

Question How to emulate button pressing?

Discussion in 'UGUI & TextMesh Pro' started by t1ny_bear, Mar 9, 2023.

  1. t1ny_bear

    t1ny_bear

    Joined:
    Oct 2, 2020
    Posts:
    16
    Hello, Unity Forum!
    I would like to simulate some press on button faking, wrote some extension method:
    Code (CSharp):
    1. public static void SimulateEvent<T>(this Button button) where T : IEventSystemHandler
    2.         {
    3.             ExecuteEvents.Execute<T>(button.gameObject, new PointerEventData(EventSystem.current), (x,y) => {} );
    4.         }
    In the user code I call it as
    Code (CSharp):
    1. button.SimulateEvent<IPointerDownHandler>();
    Execute returns true, but visually happens nothing.

    Could someone advice how to do it properly?
    Thanks for your attention!
     
  2. karliss_coldwild

    karliss_coldwild

    Joined:
    Oct 1, 2020
    Posts:
    601
    You are passing a lambda which does nothing to ExecureEvents.Execute. You can find plenty of examples how it gets used in ugui source code.

    For pointer down you will need to do either:
    Code (CSharp):
    1.             ExecuteEvents.Execute<T>(button.gameObject, new PointerEventData(EventSystem.current), (x,y) => x.OnPointerDown((PointerEventData)y) );
    Code (CSharp):
    1.             ExecuteEvents.Execute<T>(button.gameObject, new PointerEventData(EventSystem.current), ExecuteEvents.pointerDownHandler ) );

    Few additional notes since you need pass approriate function as third argument, you won't be able to write a generic SimulateEvent function like that.

    Another thing you should watch out is passing meaningful event data. In some cases the GUI code will actually check the fields passed event data and change it's behavior based on that.