unity+計時器,隨時開啟

WalkingSnail發表於2024-05-04
 // 定義定時器容器
    Dictionary<string, WaitForSecondsRealtime> RealtimeDict = new Dictionary<string, WaitForSecondsRealtime>();
    // 剩餘時長
    private float timeRemaining;
 
    // 開始計時
    public void StartTimer(float duration)
    {
    
        timeRemaining = duration;
        RealtimeDict.Add("Realtime", new WaitForSecondsRealtime(timeRemaining));
        StartCoroutine(TrackTimeCoroutine());
        
    }
 
    // 跟蹤時間的協程
    private IEnumerator TrackTimeCoroutine()
    {
        while (timeRemaining > 0)
        {
            // 等待一段實時時間
            WaitForSecondsRealtime timer = RealtimeDict["Realtime"];
            yield return timer;
            timeRemaining = 0;
            
    Debug.Log("定時器完成程式碼邏輯");
        }
    }
    
    // 更新time
    public void UpdateTime()
    {
        WaitForSecondsRealtime timer = RealtimeDict["Realtime"];
        if(timer != null){
            timer.Reset();
        }
        
    }
 
    // 獲取剩餘時長
    public float GetTimeRemaining()
    {
          return timeRemaining;
    }
 

改良後:

 float currentTime=0;

    
  
    // 剩餘時長
    private float timeRemaining=0;

    // 開始計時
    public void StartTimer(float duration)
    {

        timeRemaining = duration;
        StartCoroutine(TrackTimeCoroutine());

    }

    // 跟蹤時間的協程
    private IEnumerator TrackTimeCoroutine()
    {
        while (timeRemaining > 0)
        {
            // 等待一段實時時間
            WaitForSecondsRealtime timer = new WaitForSecondsRealtime(1);
            yield return timer;
            timeRemaining -= 1;
            Debug.LogWarning("定時器完成程式碼邏輯:GetTimeRemaining:" + GetTimeRemaining());

        }
        Debug.LogWarning("定時器完成程式碼邏輯:GetTimeRemaining:" + GetTimeRemaining());

    }

 

    // 獲取剩餘時長
    public float GetTimeRemaining()
    {
        return timeRemaining;
    }

相關文章