【问题标题】:Simple "Traffic" light script in C#C# 中的简单“交通”灯光脚本
【发布时间】: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


【解决方案1】:

这是适用于其他可能需要它的任何人的最终代码,可能很乱但它有效:)。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TrafficLight : MonoBehaviour
{
    public GameObject redLight;
    public GameObject greenLight;
    
    void Start()
    {
        StartCoroutine (lightSwitch());
    }

    IEnumerator lightSwitch()
    {
        while (true)
        {
            redLight.SetActive(true);
            greenLight.SetActive(false);
            yield return new WaitForSeconds(10);
            
            redLight.SetActive(false);
            greenLight.SetActive(true);
            yield return new WaitForSeconds(10);
        }
    }
}

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:

您不应该在Update() 中启动协程。这将启动一堆新的 while 循环(因为您在协程中使用了一个 while 循环),即使您没有使用 while 循环,这仍然会最终每帧切换灯光并产生一堆问题。

而是在Start() 函数中启动协程。此外,您需要在两个开关后让步,而不仅仅是在中间(否则只是立即取消开关)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    • 2013-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多