Unity 4.6 uses anonymous delegate to handle uGUI control event binding, and delegateugui

Source: Internet
Author: User

Unity 4.6 uses anonymous delegate to handle uGUI control event binding, and delegateugui

Recently, we are trying uGUI for the new version of Unity 4.6. Many operations of Unity should be specified in Inspector. This method is very easy to use, and even some planning and art personnel can do something very well. But in some cases, it is not suitable for the program. For example, I have 10 skill buttons that trigger a skill when a button is clicked. If each button is manually bound to a function, isn't it difficult? In addition, the bound function still has no parameters. Do you need to write 10 functions to process the same logic? I instantly felt a lot of pain. Do you have it?

In this case, a solution is provided. Suppose we have edited n Button objects:

Public class UISkillPanel: MonoBehaviour {// Use this for initialization void Start () {// List of player skill data obtained <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); // -- use anonymous delegate to process Button events. 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 ));}}

This method dynamically transmits the spell parameter and solves the relationship between the button and skill. :)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.