Unity 4.6的使用匿名delegate處理uGUI控制項事件綁定,delegateugui

來源:互聯網
上載者:User

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參數,也解決了按鈕與技能對應的關係問題。:)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.