I’m working on a rhythm game and I made a function that invokes after a specified number of “beats” in the music.
Here it is…
public static void InvokeAfterBeats(this MonoBehaviour me, Action theDelegate, int beats, BeatMaster beatHandler)
{
if (beats > 0)
{
me.StartCoroutine(ExecuteAfterBeats(theDelegate, beats, beatHandler));
}
else
{
theDelegate();
}
}
private static IEnumerator ExecuteAfterBeats(Action theDelegate, int beats, BeatMaster beatHandler)
{
int currentBeat = 0;
bool canBeat = false;
while (currentBeat < beats)
{
if (!beatHandler.fixedEnemyBeat)
{
canBeat = true;
}
if (beatHandler.fixedEnemyBeat && canBeat)
{
currentBeat++;
canBeat = false;
}
yield return new WaitForSeconds(0.0166666f);
}
theDelegate();
}
How exactly would I go about canceling this? I don’t want to cancel it based on the IEnumerator name cause I might have more than one going at once and I only want to cancel one or two of them.
Preferably I would cancel it based on the Action that was given to it when it was called. Kinda like CancelInvoke.
When you call StartCoroutine(), it returns an object of type Coroutine. You can pass that object to a StopCoroutine() call to tell it which coroutine to stop.
Coroutine firstcoroutine = StartCoroutine(MyFunction(1));
Coroutine secondCoroutine = StartCoroutine(MyFunction(2));
// Stop just the first one
StopCoroutine(firstCoroutine);
Using delegates as keys in a Dictionary is probably a bad idea, because two delegates that do the same thing or call the same function will not necessarily compare as equal.
I don’t know where your Actions are coming from. If they are explicitly saved somewhere as Actions and you are reusing the same references, then it might be OK. But that would be an unusual thing to do.
You probably want to figure out some higher-level organizational structure you can impose on your data.
But that string has to be the method name, not an arbitrary string you’ve made up. As the OP points out, migueltuliompg is running multiple concurrent coroutines that all use the same method, so stopping by method name isn’t specific enough.
Also, the documentation you linked says that you shouldn’t stop a coroutine via string unless you also started it via string (though it doesn’t specify what will happen if you try).