无限循环崩溃,但不在更新功能中

时间:2018-05-17 16:51:14

标签: loops unity3d time while-loop timer

这些脚本导致Unity挂起。我在这里缺少什么?

我知道这可能是有史以来最愚蠢的问题,考虑Unity如何处理循环。但是我发誓我以前写过这个并且让它工作......我做错了什么?我得到的循环是无限的,但它必须不断迭代。

Timer.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Timer{
    float tickTime;
    float lastTicktime;
    bool timerRunning = false;

    public Timer (float tickTime) {
        this.tickTime = tickTime;
    }

    public void StartTimer() {
        timerRunning = true;
        lastTicktime = Time.time;
        GenerateTicks ();

    }

    public void StopTimer () {
        timerRunning = false;
    }

    void GenerateTicks () {
        while (timerRunning) {
            if ((Time.time - lastTicktime) > tickTime) {
                Debug.Log ("Tick");
                lastTicktime = Time.time;
            }
        }
    }
}

实施

Timer timer;
    void Start () {
        timer = new Timer (triggerTime);
        timer.StartTimer ();
}

1 个答案:

答案 0 :(得分:4)

代码永远不会退出while(timerRunning)循环,因为你永远不会在所述循环中执行timerRunning = false

此外,即使您在timerRunning = false部分中添加了if ((Time.time - lastTicktime) > tickTime) { },也会挂起Unity主线程的执行,直到该条件为true(基本上,Unity会停止,直到至少tickTime秒已过。)

如果您需要使用计时器并让Unity执行,请使用Coroutines。

编辑:回答你的评论,修改你的代码:

using UnityEngine;
using System.Collections;

public class Timer {

    float tickTime;
    float lastTicktime;
    bool timerRunning = false;

    public Timer(float tickTime) {
        this.tickTime = tickTime;
    }

    public IEnumerator StartTimer() {
        timerRunning = true;
        lastTicktime = Time.time;
        while (timerRunning) {
            if ((Time.time - lastTicktime) > tickTime) {
                Debug.Log("Tick");
                lastTicktime = Time.time;
                timerRunning = false;
            }
            yield return null;
        }
    }
}

实现:

private Timer timer;
private IEnumerator timerCoroutine;

private void Start() {      
    timer = new Timer(triggerTime);
    timerCoroutine = timer.StartTimer();
    StartCoroutine(timerCoroutine);
}