继上一篇,我们要调用Fade方法,我们就要使用unity3D中的StartCoroutine方法。
下面我们就通过StartCoroutine方法来开启定义协程Fade,代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class CoroutineTest : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKey(KeyCode.LeftArrow))
StartCoroutine("Fade");
}
IEnumerator Fade()
{
for (float f = 1f; f >= 0; f -= 0.1f)
{
Color c = GetComponent<Renderer>().material.color;
//Color c = renderer.material.color;
c.a = f;
GetComponent<Renderer>().material.color = c;
yield return null;
}
}
}
将该脚本挂载在某个游戏对象上,开始运行游戏,在游戏运行期间按下键盘方向左键便开启了一个协程Fade,也就实现了游戏对象随着时间而逐渐变得透明的功能。
注:
在场景中创建一个cube并且拖入材质,拖入以上脚本,画红线的地方是我自己选择的,运行场景。
注:这就是最终结果。
但是执行过脚本之后你会发现一个问题,那就是协程是每帧都会恢复执行的,如果想要一个延时的效果,经过一段时间之后再恢复执行是否有可能呢?答案是可以的。这里又会引入一个新的类WaitForSeconds。通过它可以实现延时恢复执行逻辑的需求。
我们现在做一个使用WaitForSeconds类的实例:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ExampleClass : MonoBehaviour {
// Use this for initialization
void Start () {
StartCoroutine("Example");
}
IEnumerator Example()
{
print(Time.time );
yield return new WaitForSeconds(5);
print(Time.time);
}
// Update is called once per frame
void Update () {
}
}
将这个脚本挂在场景内摄像机上,然后运行游戏,可以在unity3D的输出窗口看到打印出的语句。
注:看到使用WaitForSeconds使协程Example推迟了5秒才恢复执行之后的逻辑。
接下来我们要做的是使用WaitForSeconds来延缓游戏物体变得透明。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class CoroutineTest : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKey(KeyCode.LeftArrow))
StartCoroutine("Fade");
}
IEnumerator Fade()
{
for (float f = 1f; f >= 0; f -= 0.1f)
{
Color c = GetComponent<Renderer>().material.color;
//Color c = renderer.material.color;
c.a = f;
GetComponent<Renderer>().material.color = c;
yield return new WaitForSeconds(.5f);
}
}
}
效果图: