Making a timer in Unity

2019-08-30 08:14发布

I have a problem in Unity. I need a countdown in my project. But this countdown will count 2 times. For example, 3 seconds a job will be done, 2 seconds another job will be done and these works will continue.

2条回答
唯我独甜
2楼-- · 2019-08-30 08:34

Based in the example of use you gave where an object first turn right, then turns left:

consider an object. When the program start, turn right for 3 seconds, after turn left for 1 second. they will repeat continuously. two counters will follow each other.

Below I give you two timers which are executed sequentially: first one will last 3 seconds and the second one other one 2 seconds. Once one counter finish the other one will starts, this will be repeated in an infinite loop.

float counterTask1 = 3f;
float counterTask2 = 2f;
float timer;
bool chooseTask;

void Start(){
    //Initialize timer with value 0
    timer = 0;
    chooseTask = 1;
}

void Update ()
{
    // Add the time since Update was last called to the timer.
    timer += Time.deltaTime;

    // This will trigger an action every 2 seconds
    if(chooseTask && timer >=  counterTask1)
    {
        timer -= counterTask1;
        chooseTask = 0;
        #Do Task 1 Here
    }else if(!chooseTask && timer >= counterTask2)
    {
        timer -= counterTask2;
        chooseTask = 1;
        #Do Task 2 Here
    }
}

I am not sure if this is what you were looking for. In any case there are lot of questions already asked about timers in Unity. Check some of them: https://stackoverflow.com/search?q=timer+in+Unity

查看更多
放我归山
3楼-- · 2019-08-30 09:00

Couroutines (and more Coroutines)

Coroutines do exactly the thing you want to do.

private IEnumerator Countdown2() {
    while(true) {
        yield return new WaitForSeconds(2); //wait 2 seconds
        //do thing
    }
}

private IEnumerator Countdown3() {
    while(true) {
        yield return new WaitForSeconds(3); //wait 3 seconds
        //do other thing
    }
}

You then start them off by calling in your Start() method (or where ever):

void Start() {
    StartCoroutine(Countdown2());
    StartCoroutine(Countdown3());
}

Note that both countdown methods will do their thing forever unless one of three things happens:

  1. StopCoroutine(...) is called, passing in the reference returned by StartCoroutine
  2. The countdown function itself returns (which will not happen unless it breaks out of the infinite while(true) loop)
  3. The coundown function itself calls yield break

Also note that in the event both coroutines should resume at the same time (e.g. at 6 seconds) coroutine 2 will execute first (as it was started first), unless some other effect intervenes (e.g. one of the loops has another yield instruction, one of the loops is terminated, etc).

查看更多
登录 后发表回答