Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How CancelInvoke() works in unity

Tags:

c#

unity3d

So I thought a lot about phrasing the heading of this thread but somehow ended up with a dumb question.

What I want to do :

I want to refactor my code so that I can replace all Invoke(string,seconds) calls in unity with my own method(Routine) IEnumerator WaitAndExecute(float time, Action callback) which waits for "time" seconds and executes the "callback".

Reason : I don't want to pass methods as strings as it makes it difficult to find references in IDE.

Problem : My CancelInvoke() doesn't work on methods that were executed without Invoke().

So I want to know how unity keeps tracks of things and references of invoked methods to later cancel them.

like image 317
Jajan Avatar asked Oct 29 '22 22:10

Jajan


1 Answers

This is what i have understood from your question : you have some invokes and some coroutines in your code.

Previously before refactoring you have had to call CancelInvoke() but for now you should pair any CancelInvoke() with StopAllCoroutines() on any MonoBehaviour.

Also another thing to mention is that your method

IEnumerator WaitAndExecute(float time, Action callback)

is not a good one, you should also pass MonoBehaviour to start coroutine exactly on the object that want to run Callback. for example :

public class Player : MonoBehaviour
{

void Start()
{

    Utils.WaitAndExecute(this , 5, callback);
}

public void callback()
{
    // blah blah blah
}

}

public class Utils
{
public void WaitAndExecute(MonoBehaviour objectToRun , float time, Action callback)
{
    // ...
    objectToRun.StartCoroutine(...);
    // ...
}
}

This way you can easily stop coroutines inside Player script:

StopAllCoroutines();
like image 101
AminSojoudi Avatar answered Nov 15 '22 09:11

AminSojoudi