如何在EditorWindow中暂停/继续计时器?

时间:2018-09-26 01:05:31

标签: c# unity3d

void OnGUI()
    {
        pauseCounting = GUILayout.Toggle(pauseCounting, "Pause timer");
        Timer();
    }

然后:

private void Timer()
    {
        if (stopCounting == false)
        {
            EditorGUILayout.LabelField("Count Each:", countTime + " Secs");

            if (waitForUI)
                timeToCount = nextCountTime - EditorApplication.timeSinceStartup;

            EditorGUILayout.LabelField("Next Count:", timeToCount.ToString() + " Sec");
            if (waitForUI == false)
            {
                timeToCount = 30;
                waitForUI = true;
            }

            this.Repaint();

            if (EditorApplication.timeSinceStartup > nextCountTime)
            {
                nextCountTime = EditorApplication.timeSinceStartup + countTime;
            }

        }
        else
        {
            EditorGUILayout.LabelField("Counting:", countTime + " Secs");
            EditorGUILayout.LabelField("Next Count:", countToSave.ToString() + " Sec");
        }
    }

问题是我现在使用的是EditorApplication.timeSinceStartup,如果我将stopCounting标志更改为true,然后又返回false,它将使用EditorApplication.timeSinceStartup进行计算,并且不会从停止点继续。我希望,如果stopCounting为true,然后再次为false,则从上次暂停开始继续计时。

1 个答案:

答案 0 :(得分:2)

在您的班级中,添加一个字段以记录总的滴答时间:

double timerRecord;

在您的onEnable中,将其初始化:

timerRecord = EditorApplication.timeSinceStartup;

在您的OnGUI()中,添加一些逻辑以检查“重新启动”操作:

var shouldStop = GUILayout.Toggle(stopCounting, "Pause timer");
if(!shouldStop && stopCounting)
{
    // in this case, you restarted the timer.
    timerRecord = EditorApplication.timeSinceStartup;
}
stopCounting = shouldStop;
Timer();

最后在您的Time()中,将所有的'EditorApplication.timeSinceStartup'替换为'timerRecord',最后,将'timerRecord'的值替换为'EditorApplication.timeSinceStartup'。

timerRecord = EditorApplication.timeSinceStartup;