Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attach new script to button onclick event in unity3d c#

Tags:

c#

unity3d

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.

like image 923
Neeraj Kumar Avatar asked Jul 26 '15 11:07

Neeraj Kumar


People also ask

How do I use buttons in unity script?

To insert a button, right click in the Scene Hierarchy and go to Create → UI → Button. If you do not have an existing Canvas and an EventSystem, Unity will automatically create one for you, and place the button inside the Canvas as well.

How do you add a listener to a button in unity?

Use UnityEvent. AddListener to extend the onClick click events. The added UnityAction is called when the Button press is released. A Button can have multiple listeners.


1 Answers

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.

like image 190
Neeraj Kumar Avatar answered Oct 03 '22 19:10

Neeraj Kumar