【问题标题】:If loop using timeSinceLevelLoad variable如果循环使用 timeSinceLevelLoad 变量
【发布时间】:2016-03-15 16:59:40
【问题描述】:

我有一个初始化为 true 的切换按钮,当它被关闭时,它应该触发一个函数,该函数对经过的每一秒进行减法。

要减去的变量名为 TEMPERATURE,它应该每秒减去 1,直到达到 0。为了计算秒数,我使用名为 TimeSinceLevelLoad 的 Monobehaviour 变量。

我构建了 I 函数,但减法永远不会发生,你能帮帮我吗?

using UnityEngine;
using System.Collections;
using Assets.Code.PowerPlants;

public class thermoPowerControlPanel : MonoBehaviour {

    private ThermoElectric thermo;

    public bool t1= true;
    int temperature;
    private int tempUP = 10;
    private int tempDOWN = 1;
    private int mark;
    private int i =0;

    public thermoPowerControlPanel (){
        temperature = 100;
    }

    public void turbine1State (bool t1) {
        Debug.Log (temperature);

        if (i ==0) {
            mark = (int)Time.timeSinceLevelLoad;
            i = 1;
        } 

        if (t1 == false) {
        ThermoElectric.t1Bool = t1;
            if (temperature != 0) { 
                    if (mark + 1  == (int)Time.timeSinceLevelLoad ) {
                        temperature = temperature - tempDOWN;
                        i = 0;
                    Debug.Log (temperature);
                    }
            }
        }
    }
    }

bool t1 工作正常,我已经检查过了,它变为 False。

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    这有点太复杂了。也许你应该研究协程?

    你可以像这样制作一个方法(协程)

    private IEnumerator decreseTemperature()
    {
        for (int i = 0; i < temperature; i++) // this will make couroutine cycle
        {
            yield return new WaitForSeconds(1.0f); // this makes coroutine wait for 1 second
            temperature = temperature - tempDown;
        }
    }
    

    您可以轻松地启动和停止协程:

    StartCoroutine(decreseTemperature());
    
    Stop Coroutine(decreseTemperature());
    

    您可能需要根据需要调整此代码,但协程在此类问题中非常有用。

    【讨论】:

    • 非常感谢您的回复,也许我可以改用这个条件
    • 试试吧,我真的觉得协程很有用。祝你好运!
    • for (int i = 0; 温度 >0; i++)
    • 我需要解决这个问题,但我会给你答案,因为这是一个很好的解决方案。
    • 将 ienumerable 更改为 ienumerator。现在这是正确的,还请记住,您必须在循环条件中使用“i”
    猜你喜欢
    • 1970-01-01
    • 2013-12-03
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    相关资源
    最近更新 更多