簡體   English   中英

需要一些幫助,在 C# 中運行控制台計時器,有什么想法嗎?

[英]Need some help, running a console timer in C#, any ideas?

由於 C# 非常令人畏懼,因此我正在尋求有關如何根據代碼中的注釋對其進行調試的幫助。 總而言之,我有一個在控制台中運行的計時器(這里是菜鳥,代碼復制粘貼或教程)並且數字 ONE 和 GO 同時運行,我還沒有找到在預期結果之后停止計時器的方法是已達到,我們將不勝感激!

using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
    public int startTime = 4;

    void Start()
    {
        InvokeRepeating("timer", 1.0f, 1.0f);
    }

    void timer()
    {
        if (startTime > 0)
        {
            if (startTime == 3)
            {
                Debug.Log("THREE");
                startTime -= 1;
            }
            else
            {
                if (startTime == 2)
                {
                    Debug.Log("TWO");
                    startTime -= 1;
                }
                else
                {
                    Debug.Log("ONE");
                    startTime -= 1;
                    //Precent "ONE" and "GO!" from running simultaneously
                }
            }
        }

        if (startTime == 0)
        {
            Debug.Log("GO!");
            //Fix "GO!" playing to console indefinetly after timer is finished
        }

        void Update()
        {

        }
    }
}

為此,您可以使用 CancelInvoke方法,方法是將方法名稱作為參數傳遞給引號,您可以在 startTime 變為 0 時調用它。您可以安全地刪除 Update 方法

public int startTime = 3;

void Start()
{
    InvokeRepeating("timer", 1.0f, 1.0f);
}

void timer()
{
    //go throw all the cases
    switch (startTime)
    {
        case 0:
            Debug.Log("GO!");
            CancelInvoke("timer");
            break;
        case 1:
            Debug.Log("ONE");
            break;
        case 2:
            Debug.Log("TWO");
            break;
        case 3:
            Debug.Log("THREE");
            break;
    }

    //substract - from time
    startTime -= 1;

}

或者使用這個協程

void Start()
    {
        StartCoroutine("timer");
    }
    IEnumerator timer()
    {
        //debug the time
        Debug.Log(startTime); //you can use the if statement do show it as text or use any humanizer **C# 101 series**
        startTime--; //here we substract 1 from time
        //we wait for 1s
        yield return new WaitForSeconds(1); 
        //if the time still >= 0 repeat
        if(startTime >=0)
            StartCoroutine("timer");
    }

我想你想要 //if (startTime == 0) else { Debug.Log("GO!"); //修復“開始!” 計時器結束后無限期地播放到控制台}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM