首先,协程的准备工作
关键的代码段,写在了OnGUI中,在判断按钮的if语句块下
if (GUI.Button(new Rect(40, 50, 150, 50), "被击"))
{
StartCoroutine(WaitBehit());
}
然后创建新的结构,包含了协程需要执行的具体内容,固定写法 IEnumerator name()
IEnumerator WaitBehit()
{
// GetComponentInChildren会在该物体各个子物体的属性中查找对应的值(SkinnedMeshRenderer)
var smr = Monster.GetComponentInChildren<SkinnedMeshRenderer>();
//没有返回类型,所以不需要设置
smr.sharedMaterial.SetColor("_Color", Color.white);
yield return new WaitForSeconds(0.05f);
smr.sharedMaterial.SetColor("_Color", Color.black);
}
简单易懂,按下按钮后, 执行SetColor为白色,等待0.05秒后,执行SetColor为黑色
但是缺少了过渡效果,下面我们在中毒的效果中加入此项
if (GUI.Button(new Rect(40, 120, 150, 50), "中毒"))
{
StartCoroutine(WaitDu());
}
同样的,协程固定写法,然后是创建协程的结构
IEnumerator WaitDu()
{
// 声明一个_time为0的数值进入循环
float _time = 0;
// 始终为真,会一直循环,所以利用yield break打破循环,条件是当_time大于2时
while (true)
{