Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to assign OnClick for UI Button generated in runtime?

Discussion in 'UGUI & TextMesh Pro' started by vladstorm_, Oct 3, 2015.

  1. vladstorm_

    vladstorm_

    Joined:
    Nov 26, 2013
    Posts:
    184
    Hi,

    So, I'm generating a Button in runtime.

    Code (CSharp):
    1. var myButton = (GameObject)Instantiate(button_prefab, Vector3.zero, Quaternion.identity);
    How can I assign the OnClick event in runtime?
    or how can I listen to button OnClick event anyhow ?

    also. within that OnClick event - How can I define from which object if was called. In case the event function could be called from different buttons.
     
    Last edited: Oct 4, 2015
  2. Senshi

    Senshi

    Joined:
    Oct 3, 2010
    Posts:
    557
    Unlike all other Button events, onClick actually has a dedicated property for it!

    Code (csharp):
    1. Button button = myButton.getComponent<Button>();
    2. //next, any of these will work:
    3. button.onClick += myMethod;
    4. button.onClick.AddListener(myMethod);
    5. button.onClick.AddListener(delegate{MyMehtod();})
    6. button.onClick.AddListener(() => {MyMethod();});
    Be sure to use this forum's search function though; this question has been asked a ton of time before already! ;)
     
    Last edited: Oct 4, 2015
  3. vladstorm_

    vladstorm_

    Joined:
    Nov 26, 2013
    Posts:
    184
    @Senshi
    thank you. ill check it out.
    i tbh didnt find another answer. and also unity forum/answers worked really strange today. i couldn't load some pages.
     
    Senshi likes this.
  4. vladstorm_

    vladstorm_

    Joined:
    Nov 26, 2013
    Posts:
    184
    @Senshi
    so, it doesn't work :<
    i tried this
    Code (CSharp):
    1. UnityEngine.UI.Button btn = myButton.GetComponent<UnityEngine.UI.Button>();
    2. btn.onClick.RemoveAllListeners();
    3. btn.onClick.AddListener( () => { Debug.Log("test"); });
    and this also doesn't work
    Code (CSharp):
    1.             UnityEngine.UI.Button btn = b.GetComponent<UnityEngine.UI.Button>();
    2.             btn.onClick.RemoveAllListeners();
    3.             btn.onClick.AddListener( delegate{ Debug.Log("test"); } );
    EDIT: it works actually.
    the problem was different. I'm using Magic Mouse on OSX and sometimes when I have a message that the battery is low -> Unity game window stops receiving mouse click events. I'll make new thread about it.
     
    Last edited: Oct 4, 2015
    Senshi likes this.
  5. Senshi

    Senshi

    Joined:
    Oct 3, 2010
    Posts:
    557
    Glad you got it to work! =) Also forgot to add a lambda expression in my example, thanks for reminding me. Edited my answer for future readers.
     
    guneyozsan and vladstorm_ like this.
  6. MrLucid72

    MrLucid72

    Joined:
    Jan 12, 2016
    Posts:
    962
    How do you do this in 5.6? When I try, I get this:

    upload_2017-9-3_17-40-42.png
     
  7. Senshi

    Senshi

    Joined:
    Oct 3, 2010
    Posts:
    557

    Yeah, I noticed this as well. You can just use the longhand form instead:

    Code (CSharp):
    1. doneBtn.onClick.AddListener(onDoneBtnClick);
    Or for lambdas (anonymous methods):

    Code (CSharp):
    1. doneBtn.onClick.AddListener(() => {DoThingWithParameters("foo", 42);});
     
    siddharth3322 and MrLucid72 like this.
  8. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    Sorry to necro, but i'm have a problem with this, not the first time using this sort of thing.
    on a previous project i had this and it worked perfectly, same projects on 2017.3.
    where go is the GameObject with the Button, buildObject is a GameObject in the class and parts points to a game object in the array.
    Code (CSharp):
    1. go.GetComponent<Button> ().onClick.AddListener (() => {buildObject = parts[i];});
    Doing pretty much the same thing on a new project and the onClick event won't register,
    I've tried setting other stuff on the button to verify i'm getting the button, also no syntax errors anywhere.
    this is the loop creating the UI buttons.
    I'm looking in the inspector after this code runs and the buttons onClick event list is empty.
    Code (CSharp):
    1.         for (int i = 0; i < playerUnits.Length; i++) {
    2.            
    3.             GameObject go = (GameObject)Instantiate (UnitUIPrefab, units);
    4.             go.GetComponentInChildren<Text> ().text = playerUnits[i].name;
    5.             go.GetComponentInChildren<Image> ().sprite = playerUnits[i].icon;
    6.             go.GetComponent<Button> ().onClick.AddListener( (() => {Debug.Log("OnClick");}));
    7.         }
     
  9. chrixxxtopher

    chrixxxtopher

    Joined:
    Apr 8, 2018
    Posts:
    6
    Did you solve this? I am having the same problem
     
  10. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    Not really, i dont have any clue as to why it doesn't work.
     
  11. Kamyker

    Kamyker

    Joined:
    May 14, 2013
    Posts:
    1,085
    Non-persistent listeners are not visible in inspector.
     
  12. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    Doesn't change the problem, thanks for the info though.
     
  13. zyonneo

    zyonneo

    Joined:
    Apr 13, 2018
    Posts:
    386
    What if I am instantiating many buttons through loop....Should I add listeners to each of them?It is a bit confusing...
     
  14. ImFromTheFuture

    ImFromTheFuture

    Joined:
    May 21, 2015
    Posts:
    30
    Sorry for necroing this but the last comment doesn't contain a solution to the last question asked so for future readers:
    @Kamyker is correct. Non-persistent listeners are not visible in the inspector.
    To solve this you need to use AddObjectPersistentListener or AddPersistentListener

    UnityEventTools.AddPersistentListener(myBtn.onClick, new UnityAction(methodName));


    A very good example for this can be found here: https://stackoverflow.com/questions...o-button-onclick-event-in-unity-editor-script
    and also here: https://stackoverflow.com/questions/39704905/using-unityeventtools-removepersistentlistener
    Cheers!
     
    ElProfessArt and MurphyMurph_21 like this.
  15. Fangh

    Fangh

    Joined:
    Apr 19, 2013
    Posts:
    274
    @ImFromTheFuture :

    Warning : Your answer does not work if the buttons has to be setted at runtime because you are using UnityEditor library.
     
  16. MurphyMurph_21

    MurphyMurph_21

    Joined:
    Jul 3, 2020
    Posts:
    73
    Thanks man a great help, your awesome, God bless!