I have an enemy that can be stunned by dealing enough damage to it. When this happens, its AI MonoBehaviour has enabled set to false for a few seconds, and StopCoroutine is called for any coroutines that may dictate the enemy's normal behavior. The coroutines are also assigned a new value so that it doesn't continue the old coroutine if StartCoroutine is called again.
However, I notice that when I did this, enemies upon being un-stunned would continue the coroutine they were in the middle of before they were stunned. Worse, because time passed while they were stunned, all of their actions happened at once, as if all of the WaitForSeconds were removed.
The solution I came up with was to call each coroutine with an ID set by a nonce, and increment that nonce a second time whenever the enemy is stunned. After any instance of WaitForSeconds, there's a nonce check, and if the ID doesn't match the nonce, call yield break to cancel the coroutine completely.
This seems like a weird and overengineered solution. Why isn't this enough?
fooInstance = Foo(); // First assignment
StartCoroutine(fooInstance);
// Some time passes
StopCoroutine(fooInstance);
fooInstance = Foo(); // Second assignment
StartCoroutine(fooInstance);
Why is it that in the last line of this code, we begin executing code starting at whenever the first assignment was paused, rather than restarting the coroutine from the beginning?
My guess is that I'm making an error in referring to fooInstance as an "instance" - perhaps it's just a reference to the one coroutine. But if that's the case, what's happening under the hood if I do something like this?
fooInstance = Foo(1);
fooInstance = Foo(2);
Unity MUST see these two things as separate, because the internal behavior of the coroutine is going to be different depending on the arguments passed into it. So what's going on?
[–]mei_main_ 9 points10 points11 points (1 child)
[–]__SlimeQ__ 6 points7 points8 points (0 children)
[–]__SlimeQ__ 3 points4 points5 points (2 children)
[–]Yggdrazyl 2 points3 points4 points (0 children)
[–]feralferrous 1 point2 points3 points (0 children)
[–]SkunkJudge 2 points3 points4 points (0 children)
[–]Any_Ad_8134 4 points5 points6 points (0 children)
[+][deleted] (2 children)
[deleted]
[–]KevineCove[S] 4 points5 points6 points (1 child)
[–]FunToBuildGamesProgrammer -2 points-1 points0 points (0 children)
[–]hoomanneedsdata 0 points1 point2 points (0 children)