uGUI使用代碼動態添加Button.OnClick()事件(Unity3D開發之十二),uguibutton.onclick
猴子原創,歡迎轉載。轉載請註明: 轉載自Cocos2Der-CSDN,謝謝!
原文地址: http://blog.csdn.net/cocos2der/article/details/42705885
uGUI出來這麼久了,也一直沒好好用用,主要是公司項目不用U3D。昨晚用了下Button,還是比較爽的。
主要說下用代碼添加button.OnClick()事件的方法(使用屬性面板添加的方法就不說了)
一、建立2D UI Panel,添加你需要的Button。
我添加了3個Button:BtnStart,BtnShop,BtnLeaderboards。
二、添加指令碼
using UnityEngine;using System.Collections;using System.Collections.Generic;using UnityEngine.Events;using UnityEngine.UI;public class MainMenu : MonoBehaviour {// Use this for initializationvoid Start () {List<string> btnsName = new List<string>();btnsName.Add("BtnPlay");btnsName.Add("BtnShop");btnsName.Add("BtnLeaderboards");foreach(string btnName in btnsName){GameObject btnObj = GameObject.Find(btnName);Button btn = btnObj.GetComponent<Button>();btn.onClick.AddListener(delegate() {this.OnClick(btnObj); });} }public void OnClick(GameObject sender){switch (sender.name){case "BtnPlay":Debug.Log("BtnPlay");break;case "BtnShop":Debug.Log("BtnShop");break;case "BtnLeaderboards":Debug.Log("BtnLeaderboards");break;default:Debug.Log("none");break;}}// Update is called once per framevoid Update () {}}
ok,測試一下,可以玩耍了。