Untiy3D通过代码创建Button

[code]csharpcode:

01 using UnityEngine;
02 using System.Collections;
03 using UnityEngine.UI;
04 public class ButtonCtrl : MonoBehaviour {
05  
06     GameObject canvas;
07     GameObject button;
08     Button _btn;
09     // Use this for initialization
10     void Start () {
11          canvas = new GameObject("Canvas"typeof(Canvas), typeof(RectTransform),typeof(CanvasScaler),typeof(GraphicRaycaster));  //创建一个GameObject  加入Canvas的组件
12          button = new GameObject("Button",typeof(Button),typeof(RectTransform),typeof(Image));  //创建一个GameObject 加入Button组件
13         button.transform.SetParent(canvas.transform);  //把Canvas设置成Button的父物体
14         _btn =  button.GetComponent
15         _btn.onClick.AddListener(Show);   //添加触发点击时执行的方法
16         _btn.onClick.RemoveListener(Show);  //移除方法
17     }
18      
19     void Show()
20     {
21         Debug.Log("what");
22     }
23     // Update is called once per frame
24     void Update () {
25      
26     }
27 }

你可能感兴趣的:(Unity)