简体   繁体   English

将新脚本附加到unity3d C#中的按钮onclick事件

[英]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. 我正在用c#创建一个新的gameobject,并试图在遇到问题时执行脚本。 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. 但此脚本无法正常工作,按钮上没有任何脚本。 在此处输入图片说明 .

I have tried these also 我也尝试过这些

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

But nothing is working. 但是没有任何效果。

I have updated unity to 5.1.2, now it is working fine. 我已经将unity更新为5.1.2,现在可以正常工作了。 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. 但是它仍然没有反映在UI中,有人说非持久性统一事件没有反映在UI中,我想是真的。

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 如果要在设计时添加回调,则应在编辑器中单击“单击”部分的右下部分中的小加号,然后选择应处理该回调的对象以及该按钮应调用的功能

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
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM