Search Unity

Button onClick doesnt work as expected.

Discussion in 'Getting Started' started by gab123, Mar 25, 2017.

  1. gab123

    gab123

    Joined:
    Mar 6, 2016
    Posts:
    14
    Hi,
    I have a Button:

    public Button reset;

    And I added an OnClickListener to it:

    Button btn1 = reset.GetComponent<Button>();
    btn1.onClick.AddListener(restartOnClick);


    The function looks like this:

    public void restartOnClick(){

    Debug.Log ("Restart");
    }

    The problem is that after clicking this button the whole game stops working for few seconds (10 or 15 seconds) and than on the console I can see around 90 messages saying "Restart". (I've expected one message immediately after clicking the button). How can I fix it?
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    I dunno — perhaps you're doing something silly like calling AddListener in your Update event (so it's getting added a gazillion times).

    Why are you adding the listener from code at all? Your restartOnClick method is public; you should probably just hook this event up in the inspector.

    There are important differences between events hooked up in code and events hooked up in the inspector... perhaps my video about UnityEvents will have some insights for you?
     
  3. gab123

    gab123

    Joined:
    Mar 6, 2016
    Posts:
    14
    I hooked this event in the inspector and right now it works.Thank you!
     
    JoeStrout likes this.