1

我正在尝试使用 c# 脚本在 unity3d 中使雾随着时间的推移变得更加密集

在开始时我打开它,如下代码所示

 void Start () {
    RenderSettings.fog =true;
    RenderSettings.fogDensity = 0.00f;
 }

在更新中,我每 3 秒检查一次并添加到密度,如下代码所示

 void Update () {
      StartCoroutine(updateTheFog());
 }

updateTheFog 函数是

IEnumerator updateTheFog(){

    yield return new WaitForSeconds(3); 

    RenderSettings.fogDensity+=0.01f;
}

问题是它等待 3 秒,然后自动转到 1.0,而不是每 3 秒递增 0.01

感谢任何帮助解决这个问题

4

2 回答 2

4

根据这个问题,您不应该为此使用更新,因为更新每帧运行一次并且不能延迟。而不是这样做,您可以做的是在 Start() 中启动协程并使用while(true)无限循环手动重复此操作。

void Start () 
{
    RenderSettings.fog =true;
    RenderSettings.fogDensity = 0.00f;
    StartCoroutine(updateTheFog());
}

IEnumerator updateTheFog() 
{
    while(true)
    { 
        //this makes the loop itself yield 
        return new WaitForSeconds(3); 

        RenderSettings.fogDensity+=0.01f;
    }
    //if you want to stop the loop, use: break;
}
于 2013-01-28T03:33:21.130 回答
1

Lee Taylor 所说的应该可行,但作为替代方案,您可以使用 InvokeRepeating 函数,它允许您设置一个函数以在特定时间间隔调用,有点像 .net 框架中的计时器。您甚至可以通过调用 CancelInvoke 来停止调用重复。

void Start(){
    InvokeRepeating("updateTheFog",3,3);
}
void updateTheFog(){
// do your fog stuff
if(fogDensity == 1)
    cancleInvoke()
 }
于 2013-01-31T23:27:31.390 回答