参考链接:http://www.unitymanual.com/thread-36543-1-1.html
代码如下:
using UnityEngine;
using System.Collections;
using System;
[Serializable]
public class SkillInfo {
public string skillName;//技能名称
public string imagePath;//技能图片路径
public float coolingTime;//冷却时间
public SkillInfo(string skillName, string imagePath, float coolingTime)
{
this.skillName = skillName;
this.imagePath = imagePath;
this.coolingTime = coolingTime;
}
}
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
public class SkillInfoManager : MonoBehaviour{
public List<SkillInfo> skillInfos = new List<SkillInfo>();
// Use this for initialization
void Start ()
{
Init();
for (int i = 0; i < skillInfos.Capacity; i++)
{
SkillInfo skillInfo = skillInfos[i];
GameObject btnGO = GameObject.Find(string.Format("SkillButton{0}",i));
//更新技能图片
btnGO.GetComponent<Image>().overrideSprite = Resources.Load(skillInfo.imagePath, typeof(Sprite)) as Sprite;
//绑定监听
btnGO.GetComponent<Button>().onClick.AddListener
(
delegate()
{
OnSkillButtonClick(skillInfo);
}
);
}
}
void Init()
{
//角色技能初始化,从文件或数据库中读取角色当前的技能,这里简化了
skillInfos.Add(new SkillInfo("剑", "sword", 1f));
skillInfos.Add(new SkillInfo("鞋", "shoe", 2f));
skillInfos.Add(new SkillInfo("衣", "clothes", 3f));
skillInfos.Add(new SkillInfo("斧", "axe", 4f));
}
void OnSkillButtonClick(SkillInfo skillInfo)
{
//释放技能
print(skillInfo.skillName + "释放技能!");
//进入冷却
StartCoroutine(Cooling(skillInfo));
}
IEnumerator Cooling(SkillInfo skillInfo)
{
yield return new WaitForSeconds(skillInfo.coolingTime);
print(skillInfo.skillName + "冷却完毕!");
}
}
未运行时是这样的:
运行时是这样的:
点击按钮是这样的:
这样就可以看到代码控制事件的强大吧!代码比较简单,就不解释了。。