2016-03-14 32 views
1

我有一個開關按鈕被初始化爲true,當它被關閉時,它應該觸發一個函數,對經過的每一秒進行相減。如果循環使用timeSinceLevelLoad變量

要減去的變量名爲TEMPERATURE,它應該每秒減1,直到它達到0.要計算秒數,我使用名爲TimeSinceLevelLoad的Monobehaviour變量。

我建立了我的功能,但減法永遠不會發生,你能幫助我嗎?

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); 
        } 
      } 
     } 
    } 
    } 

布爾t1工作正常,我已經檢查,它更改爲False。

回答

0

這有點太複雜。也許你應該看看協程?

您可以作出這樣

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()); 

你可能會需要將此代碼按需要調整,但協同程序在這類問題中非常有用。

+0

非常感謝您的回覆,也許我可以使用這個條件代替 –

+0

試試吧,我真的覺得協程很有用。祝你好運! –

+0

for(int i = 0; temperature> 0; i ++) –