【问题标题】:Light isn't flashing in UnityUnity 中的灯不闪烁
【发布时间】:2019-03-16 22:37:12
【问题描述】:

在解决了ReferenceError with my Flash_Light.cs script 之后,我遇到了脚本中的目标灯不闪烁的问题。

Flash_Light 脚本附加到LampPost_A_Blink1LampPost_A_Blink1 附加了一个灯(称为RedLight),并且该脚本似乎运行良好(没有警告或错误)。但是,灯不会闪烁。

我的脚本是:

using UnityEngine;
using System.Collections;

 public class Blink_Light : MonoBehaviour
 {

     public float totalSeconds = 2;     // The total of seconds the flash wil last
    public float maxIntensity = 8;     // The maximum intensity the flash will reach
    public Light myLight;

    void Awake()
    {
        //Find the RedLight
        GameObject redlight = GameObject.Find("LampPost_A_Blink1/RedLight");
        //Get the Light component attached to it
        myLight = redlight.GetComponent<Light>();
    }

    public IEnumerator flashNow()
    {
        float waitTime = totalSeconds / 2;
        // Get half of the seconds (One half to get brighter and one to get darker)

        while (myLight.intensity < maxIntensity)
        {
            myLight.intensity += Time.deltaTime / waitTime;        // Increase intensity
        }
        while (myLight.intensity > 0)
        {
            myLight.intensity -= Time.deltaTime / waitTime;        //Decrease intensity
        }
        yield return null;
    }
 }

进入播放模式时,指示灯保持亮起,而不是正常闪烁。

我该如何解决这个问题? (我有 Unity 2017.2.0f3)

【问题讨论】:

  • 老兄,你刚刚连接好你的灯。花点时间自己调试一下。 stackoverflow.com/questions/52765578/…
  • 你调用flashNow函数了吗?在 Awake 函数的末尾调用它,并使用 StartCoroutine(flashNow()) 调用它,然后查看灯光是否发生变化。
  • @Programmer 它确实改变了 - 现在,灯是关闭而不是打开(但仍然没有闪烁 D: )。

标签: c# unity3d light


【解决方案1】:

Unity 的Time.deltaTime 将在函数中相同 或在函数中循环。它改变每一帧,但调用一次函数是一帧。问题是您在while 循环中使用它而没有等待下一帧,因此您获得了相同的值。

另外,由于您不是在等待一帧,而不是在多个帧上执行代码,它只会在一帧中执行,您将无法看到灯光上的变化。解决方案是将yield return null 放入每个while 循环中。它将使while循环中的代码每帧运行,直到满足条件然后退出。

public IEnumerator flashNow()
{
    float waitTime = totalSeconds / 2;
    // Get half of the seconds (One half to get brighter and one to get darker)

    while (myLight.intensity < maxIntensity)
    {
        myLight.intensity += Time.deltaTime / waitTime;        // Increase intensity
        //Wait for a frame
        yield return null;
    }
    while (myLight.intensity > 0)
    {
        myLight.intensity -= Time.deltaTime / waitTime;        //Decrease intensity
        //Wait for a frame
        yield return null;
    }
    yield return null;
}

由于这是一个 caroutine 函数,请不要忘记使用StartCoroutine(flashNow()) 调用或启动它:

【讨论】:

  • 灯光闪烁! :D 但它在第二个 while 循环后停止(当强度为 0 时)。
  • 您当前的代码应该上升到 8,然后回到 0。您期望什么?
  • 我通过将while 循环包装在while(true) { (while loops go here) } 中来解决了停止问题。
  • 看起来您希望它永远重复。如果那是真的,那么你去。请注意,如果您想要做的是向右闪烁,那么这不是正确的方法。
猜你喜欢
  • 1970-01-01
  • 2021-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-06
相关资源
最近更新 更多