从代码中在Unity 4.6中创建Button

时间:2014-12-15 03:50:04

标签: c# button unity3d

如何从代码中在Unity 4.6中创建一个按钮(不是GUI等)?我需要能够在点击时指定操作。

我尝试向onClick添加委托或其他内容,但我无法让它发挥作用。

http://docs.unity3d.com/ScriptReference/UI.Button-onClick.html

这是我到目前为止的代码:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class ButtontitleAndAction {
    public string Title;
    public delegate void Del();

    public ButtontitleAndAction(string title, Del theaction) {
        this.Title = title;
        this.action = theaction;
    }
    public void Call() {
        Debug.Log("Call " + this.Title);
        this.action();
    }

    private Del action;
}

public class MjalertScript : MonoBehaviour {
    public Text Text;
    public GameObject gameobjectButtons;
    public GameObject gameobjectMjalertbutton;

    // Use this for initialization
    void Start() {

    }

    public void Addbuttons(ButtontitleAndAction[] buttontitles) {
        //  public void Addbuttons(string[] buttontitles) {
        GridLayoutGroup grid = this.gameobjectButtons.GetComponent<GridLayoutGroup>();
        float newwidth = 400 / buttontitles.Length;
        grid.cellSize = new Vector2(newwidth, grid.cellSize.y);
        foreach (ButtontitleAndAction buttondata in buttontitles) {
            GameObject gameobjectButton = (GameObject)Instantiate(this.gameobjectMjalertbutton);
            Transform child = gameobjectButton.transform.GetChild(0); // There should just be one child, the gameobject for the Text label.
            Text textofbutton = child.gameObject.GetComponent<Text>();
            textofbutton.text = buttondata.Title;
            gameobjectButton.transform.SetParent(gameobjectButtons.transform, false);
            Button buttonofbutton = gameobjectButton.GetComponent<Button>();
            Debug.Log("buttonofbutton: " + buttonofbutton + ", for label text: " + buttondata.Title);
            buttonofbutton.onClick.AddListener(() => {
                Debug.Log("DOO Something!");
                //buttondata.Call();
            });
        }
    }
}

按钮不会对任何水龙头做出反应。我期待&#34; DOO Something!&#34;什么东西要输出但没什么。

1 个答案:

答案 0 :(得分:0)

上面的代码实际上没有问题。我想出了真正的问题。不知何故,EventSystem项从未添加到层次结构中。只需添加一个按钮即可。实际上在我的情况下,通过代码或使用编辑器的按钮都没有工作。缺少EventSystem就是问题所在。