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. :)