Search Unity

OnClick Method not working.

Discussion in 'Unity UI (uGUI) & TextMesh Pro' started by Nerusix, Dec 26, 2016.

  1. Nerusix

    Nerusix

    Joined:
    Dec 26, 2016
    Posts:
    13
    Hey guys.
    I'm quite new and I wonder, why my onClick method doesn't work.
    Only drag and drop version works.....

    public void OnClick()
    {
    Debug.Log("test");
    }


    Thanks a lot.
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    4,858
    OnClick by itself does nothing. It's just another method. If you want to tie it in by code, you need to add a listener to the onclick call.
    Code (CSharp):
    1.  
    2. Public Button button;
    3.  
    4. void Start()
    5. {
    6.    button.onClick.AddListener(clickMethod);
    7. }
    8.  
    9. void clickMethod()
    10. {
    11.    //Stuff that happens on button click.
    12. }
    Just as a quick example. Basically telling it that when the button is clicked, it should call a method.
     
    Nerusix likes this.
  3. Zaflis

    Zaflis

    Joined:
    May 26, 2014
    Posts:
    432
    You can also link it from the inspector directly, a little less complex than adding a listener manually.
     
    Last edited: Dec 28, 2016