Neeraj Kumar
Neeraj Kumar

Reputation: 967

Attach new script to button onclick event in unity3d c#

I am creating a new gameobject from c# and trying to execute a script when clecked. here is the code.

    public void createButton(){
            GameObject kGO = new GameObject ();
            kGO.transform.parent = kCanvas.transform;
            kGO.AddComponent<Image>();
            Button btn = kGO.AddComponent<Button>();
            btn.onClick.AddListener(onButtonClick);
    }

    public void onButtonClick(){
        Debug.Log ("clicked");
    }

but this script is not working, there is not any script attached to the button. enter image description here.

I have tried these also

btn.onClick.AddListener(() => {onButtonClick()});
or
btn.onClick.AddListener(() => {onButtonClick();});
or
btn.onClick.AddListener(() => onButtonClick());

But nothing is working.

Upvotes: 6

Views: 17526

Answers (3)

Neeraj Kumar
Neeraj Kumar

Reputation: 967

I have updated unity to 5.1.2, now it is working fine. But it still do not reflect in the UI, some people are saying that non persistent unity events does not reflect in the UI, I guess that is true.

Upvotes: 3

Uri Popov
Uri Popov

Reputation: 2167

I do it like this. Its a lamba expression .

 btn.onClick.AddListener(() =>
            {
                Debug.Log("IT WORKS");
// Just handle the button clikc inside here
            });

or you could try a completely different aproach :

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
    public class TapOnNumber : MonoBehaviour, IPointerClickHandler {


        public void OnPointerClick(PointerEventData e)
        {
           //HandleClicks here
    }

Upvotes: 1

Hjorthenify
Hjorthenify

Reputation: 197

What you are trying to do here is add the callback at runtime. If you want to add the callback at design time you should instead click the little plus in the bottom right section of the On Click section in the editor and then select which object that should handle the callback and which function the button should call

Upvotes: 1

Related Questions