Unity 4.6的使用匿名delegate處理uGUI控制項事件綁定,delegateugui
最近在嘗試Unity 4.6新版的uGUI。Unity很多操作是要在Inspector中指定,這種方式十分容易上手,甚至一些策劃、美術同學也可以做一些東西,很不錯。但是有些情況對於程式來說就不適合了。例如,我有10個技能按鈕,當點擊到某個按鈕時觸發其對應的技能。如果每個按鈕都手動綁定到某個函數,是不是很麻煩?另外,綁定的這個函數還是沒有參數的,難道要寫10個函數處理同一個邏輯嗎?瞬間覺得十分蛋疼,有沒有?
針對這種情況,給出一個解法,假設我們已經編輯好了n個Button對象:
public class UISkillPanel : MonoBehaviour { // Use this for initialization void Start() { // 取得的玩家技能資料 List<SpellInfo> spellList = LocalPlayerData.Inst.SpellList; for (int i = 0; i < spellList.Count; i++) { SpellInfo spell = spellList[i]; GameObject btnGO = GameObject.Find(string.Format("SkillButton{0}", i)); //-- 使用匿名delegate處理按鈕事件 Button btn = btnGO.GetComponent<Button>(); btn.onClick.AddListener( delegate() { this.onSkillButtonClick(spell); } ); } } void onSkillButtonClick(SpellInfo spell) { Debug.Log(string.Format("Spell Button Clicked : {0}.", spell.Name)); } }
此寫法動態傳入spell參數,也解決了按鈕與技能對應的關係問題。:)