Unity 4.6的使用匿名delegate处理uGUI控件事件绑定详解
最近我在尝试使用Unity 4.6新版的uGUI。在Unity中,很多操作可以在Inspector面板中指定,这种方式易于上手,甚至策划和美术人员也能进行一些简单的操作,这一点十分不错。然而,在某些情况下,这种方式对于程序员来说并不适用。
例如,假设有10个技能按钮,当点击某个按钮时要触发其对应的技能。如果为每个按钮都手动绑定到某个函数,操作会非常繁琐。而且,绑定的函数通常没有参数,难道要为这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));
}
}
这种写法通过匿名delegate动态传入spell参数,有效地解决了按钮与技能的对应关系问题。当点击某个技能按钮时,会调用onSkillButtonClick方法,并将对应的SpellInfo对象作为参数传入,从而触发相应的技能逻辑。