Attach a new script to the onclick event button in unity3d c #

I am creating a new game object from C # and trying to execute a script while clearing. 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 does not work, the script is not attached to it. enter image description here.

I tried too

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

But nothing works.

+4
source share
3 answers

I updated unity to 5.1.2, now it works fine. But it still does not reflect in the user interface, some people say that persistent unity events do not reflect in the user interface, I think this is true.

+2
source

, , - . , "." , ,

+1

I do it like this. His expression is a lamb.

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

or you can 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
    }
+1
source

Source: https://habr.com/ru/post/1599719/


All Articles