内部更新
void Update()
{
StartCoroutine(LightsEffect());
}
然后
IEnumerator LightsEffect()
{
for (int i = 0; i < objects.Count; i++)
{
objects[i].GetComponent<Renderer>().material.color = Color.red;
}
yield return new WaitForSeconds(.5f);
for (int i = 0; i < objects.Count; i++)
{
objects[i].GetComponent<Renderer>().material.color = Color.green;
}
yield return new WaitForSeconds(.5f);
}
但这种颜色都是绿色的。
答案 0 :(得分:2)
我将如何做到这一点:
public List<GameObject> objects ;
public float delay = 0.1f;
private Renderer[] renderers;
private float lastChangeTime;
private int greenIndex = 0;
void Awake()
{
// Retrieve the renderer of each object and init to red color
renderers = new Renderer[objects.Count];
for ( int i = 0 ; i < renderers.Length ; i++ )
{
renderers[i] = objects[i].GetComponent<Renderer>();
renderers[i].material.color = Color.red;
}
// Set green color to the first one
greenIndex = 0;
renderers[greenIndex].material.color = Color.green;
}
void Update()
{
// Change color each `delay` seconds
if( Time.time > lastChangeTime + delay )
{
lastChangeTime = Time.time;
// Set color of the last renderer to red
// and the color of the current one to green
renderers[greenIndex].material.color = Color.red;
greenIndex = ( greenIndex + 1 ) % renderers.Length;
renderers[greenIndex].material.color = Color.green;
}
}
答案 1 :(得分:1)
如果你想把它作为一个协程(不是我的偏好,而是替代Hellium的答案),你需要理解一个协程不是一个循环(最后yield
没有任何帮助:as一旦完成,没有其他代码运行,方法终止。)
因此,我们将从您的原始协同方法开始,然后使循环:
IEnumerator LightsEffect()
{
while(true) {
for (int i = 0; i < objects.Count; i++)
{
objects[i].GetComponent<Renderer>().material.color = Color.red;
}
yield return new WaitForSeconds(.5f);
for (int i = 0; i < objects.Count; i++)
{
objects[i].GetComponent<Renderer>().material.color = Color.green;
}
yield return new WaitForSeconds(.5f);
}
}
现在,由于这永远不会真正终止,我们只需要启动协程一次:
void Awake()
{
StartCoroutine(LightsEffect());
}
当我们完成灯光闪烁时,我们可能还想设置逻辑来清理事物,但现在这已足够了。