Search Unity

OnClick.AddListener() Trouble

Discussion in 'Scripting' started by Frostbite23, Jun 5, 2015.

  1. Frostbite23

    Frostbite23

    Joined:
    Mar 8, 2013
    Posts:
    458
    Hello, Im making a procedually generating list using of course Javascript and Unity's UI (Thank you so much unity!).

    Right now for me its a bit of a hassle to figure it out because no one seems to provide a clear answer for me so Id thought Id ask you guys.

    Right now I'm currently trying to add an Listener event so when I click on my button it will call my function in the script, however its not like in the old days of unity now especially since you have to add a listener event for the UI button. Heres my line of code right now.

    Code (JavaScript):
    1. caseButt.onClick.AddListener( caseButtons[i].GetComponent(ListButton).OnClick() );
    I had a look at the scripting reference but they never gave an example script of how its done. While adding the first parenthesis after AddListener, monoDevelop popped an yellow box saying -

    it also says in a little grey box saying I have 1 out of two, I can see that I only have function but my question is, What do I use for the call?
     
    Last edited: Jun 5, 2015
  2. Frostbite23

    Frostbite23

    Joined:
    Mar 8, 2013
    Posts:
    458
  3. XukeLho

    XukeLho

    Joined:
    Dec 30, 2014
    Posts:
    199
    Im not that good with JS but I'll assume it's similar to C#. You want to call a function when a user clicks a button right? Are you using the new UI system to create the button?
     
  4. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    8,300
    Try this

    Code (csharp):
    1. caseButt.onClick.AddListener( function() { caseButtons[i].GetComponent(ListButton).OnClick() } );
     
  5. blizzy

    blizzy

    Joined:
    Apr 27, 2014
    Posts:
    775
    Or this:

    Code (csharp):
    1. caseButt.onClick.AddListener( caseButtons[i].GetComponent(ListButton).OnClick );
     
    Frostbite23 and karl_jones like this.
  6. Frostbite23

    Frostbite23

    Joined:
    Mar 8, 2013
    Posts:
    458
    Thanks @blizzy! I was wondering what was I missing for a minute until i realized you had no () after onClick.
     
  7. blizzy

    blizzy

    Joined:
    Apr 27, 2014
    Posts:
    775
    You need to pass a function reference to AddListener(), but in your original code, you were calling your function and passing its result instead.
     
    karl_jones likes this.
  8. Frostbite23

    Frostbite23

    Joined:
    Mar 8, 2013
    Posts:
    458
    Ahh, makes sense now.