6

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.

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

I am aware of that, but I need it to call at runtime.
1

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
    }

4 Comments

That is also not working, which version of unity are you using, this script seems to work in 4.6. I am using 5.0.0p3.
I'm using 4.6 . Sadly I dont know about 5.x They might have changed something. Is it giving you a error of some sorts ? That might help me understand what is going on.
no errors at all. but not working. I am trying with events also "forum.unity3d.com/threads/…". this is also giving error "Null reference exception". I think I should update to new version. lets see.
@Neeraj Kumar I updated my Answer with a different approach that might work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.