【发布时间】:2022-01-14 15:07:51
【问题描述】:
我有一个简单的代码,通过激活和停用红绿灯的 2 个灯光游戏对象,每 x 秒更改一次红色和绿色之间的颜色。或者这就是它应该做的,但是当我运行它时没有任何反应。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TrafficLight : MonoBehaviour
{
public GameObject redLight;
public GameObject greenLight;
void Start()
{
redLight.SetActive(true);
}
// Update is called once per frame
void Update()
{
StartCoroutine(switchLight());
}
IEnumerator switchLight()
{
while (true)
{
redLight.SetActive(true);
greenLight.SetActive(false);
yield return new WaitForSeconds(5);
redLight.SetActive(false);
greenLight.SetActive(true);
Debug.Log("loop end");
}
}
}
到目前为止,这就是我所拥有的,它没有显示任何编译器错误,并且调试表明它确实通过了循环和所有。我是 C# 新手,所以我不知道这段代码是否适合我正在尝试做的事情。任何指针将不胜感激,谢谢。
【问题讨论】:
-
由于您是在
Update中启动例程,因此您将在每一帧 中启动协程。不要那样做。
标签: c# while-loop coroutine light