making a timer

hi, im trying to make a little timer in the middle of a function , i can’t use coroutines cuz it doesnt freeze the function while counting down , and time.deltatime only works in the update method

void func()
{
blabla
//count down and wait here
do somethin
}
float timeDelay = 60f; //1 min :)
float startTime = Time.time;
call function()

function()
{
  if (startTime + timeDelay >= Time.time)
  {
  do somethin
  }
}

what coroutine setups have you tried because this doesn’t sound right.

2 Likes

i changed the ‘if’ in your code to a while loop and changed timedelay to 0.08 and unity gets stuck, what am i doing wrong ?
and this is the coroutine i used , the count is working but like a thread:

StartCoroutine("Countdown", 50);

    private IEnumerator Countdown(int time)
    {
        
        while (time > 0)
        {
            Debug.Log(time--);
           yield return new WaitForSeconds(1);
        }
        Debug.Log("Countdown Complete!");
    }

probably using a while loop… can you show your actual code?

the coroutine is pretty much a thread conceptually, it goes off and does it’s thing allowing the main game loop to continue. You need to have the “do somethin” inside the coroutine. You can get around being specific in the coroutine with delegates. i.e.

using UnityEngine;
using UnityEngine.Events; // needed for unityaction
using System.Collections; // needed for ienumerator

public class TestScript : MonoBehaviour
{
   void Start()
    {
        StartCoroutine(WaitAndDo(10f, new UnityAction(OutputSomethin)));
    }


    IEnumerator WaitAndDo(float f, UnityAction a)
   {
       yield return new WaitForSeconds(f);
       a.Invoke();
   }

    void OutputSomethin()
    {
        Debug.Log("Hi I'm a herring");
    }
}

it actually worked ty!
just to know , is there a cleaner way to do the same or is this the only way ?