While Loop with Delay

Hi there! I am working on a small mobile project and I am having a problem making a delay.
Basically I have a GameManager class that after a certain event happend, this class invokes an Event that change an entity state (my entity finit state machine, from one state to the other).
What I need to do is that my entity wait for x amount of seconds after the event was invoked, to make that transition to the other state.
One solution is making that entity class inherit from Monobehabiour and I will be able to use a coroutine. But I would like to avoid making it inherit from Monobehaviour because I dont really need that.
Is there any way that after the event was invoked, use a While loop or anything that keeps in mind the Time.Deltatime?
It should be noted that the event is invoked only once, therefore I cannot do an if/else statement that check if time was completed, if not increase counter += Time.DeltaTime.
Thank you so much for reading this thread!
Hope you could help me.

Im a novice programer. But I think you need to use a coroutine for that.

2 Likes

To start a coroutine from a non-MonoBehaviour class you can simply use any other MonoBehaviour you have a reference to. I usually have one MonoBehaviour in the scene which is just a singleton which I call Coroutiner. This way I can call Coroutiner.Instance.StartCoroutine(MyEnumeratorMethod()); from anywhere.

Alternatively, you could have an update method in all your entities which are called from outside by hand. Our you could start another thread which sleeps and then calling back (but this can be tricky… You would probably need a dispatcher to trigger your logic on the main thread the frame after the callback)

1 Like

Coroutines are the answer for this stuff, always.

You cannot do a loop to wait in Unity. That’s not a thing.

You can wrap the idea of a coroutine up in a little “do stuff later” class like this:

See notes on use at bottom, shows you how to make it do stuff in the next scene.

1 Like

Nice! Thanks you!!

1 Like

This is a nice solution. Thanks!