Search Unity

Question Button On Click from Script

Discussion in 'Scripting' started by wizenchiko, May 26, 2023.

  1. wizenchiko

    wizenchiko

    Joined:
    Dec 6, 2019
    Posts:
    12
    Hello. I would like to add OnClick() listener to my Button component in my GameObject.

    As you can see from image, I am trying to add method which takes parametr to AddListener().

    The reason why I have to make it trough the script is, bcs my object is Instantiated and On Click method is from another object in the Canvas.

    This Init() method is called at the Start(), but when the game starts, nothing is added in the On Click(). When I click on that Button i get huge error:

    ArgumentException: method arguments are incompatible
    System.Delegate.CreateDelegate (System.Type type, System.Object firstArgument, System.Reflection.MethodInfo method, System.Boolean throwOnBindFailure, System.Boolean allowClosed) (at <695d1cc93cca45069c528c15c9fdd749>:0)

    onclick.png

    Thank you
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    I've always just added a delegate like the example code shows you in the
    Button.onClick
    documentation.
     
  3. wizenchiko

    wizenchiko

    Joined:
    Dec 6, 2019
    Posts:
    12
    It didnt work for me :/

    But I solve that problem anyway.
    Code (CSharp):
    1.  Button btn = GetComponent<Button>();
    2. UnityEvent clickEvent = btn.onClick;
    3. UnityAction clickAction = new UnityAction(Show);
    4. UnityEventTools.AddPersistentListener(clickEvent, clickAction);
    EDIT : Now it works even with just btn.onClick.AddListener(Show), but it wont appear in the Inspector.
     
  4. Nad_B

    Nad_B

    Joined:
    Aug 1, 2021
    Posts:
    730
    It won't appear on Inspector because the value is set at runtime (when you play the game)