12 ms·
Coroutines are dangerous to use for initialization and I strongly recommend to be wary of that. All coroutines on a gameobject are halted if it is disabled, _a
by dleslie 6y ago
Coroutines are dangerous to use for initialization and I strongly recommend to be wary of that.
All coroutines on a gameobject are halted if it is disabled, _and do not restart_ when it is re-enabled.
For this reason it is easy to mistakenly leave a game object half-initialized, due to an enormous amount of plausible situations where some event, script or other may disable the game object.
Now, there is a work-around: have Start yield a coroutine started on a "safe" object that will never disable.
The caveat is that the caller can be destroyed during execution of the coroutine but the coroutine will persist to execute because it is on another object.
- jayd16 6y agoYou've just shifted the problem. Its better to just track your exact state and leverage the fact that you get exclusive atomic control of the main thread until you yield or return. The only lifecycle a behavior can trust is its own. Relying on other objects turns into a mess when your weak assumptions are violated. Besides causing a spaghetti mess of lifecycle tracking and callbacks and such, it leaves you wide open to the major problem if callbacks running pass the life of the thing to call back to. You've thrown away Unity's lifecycle tools by dumping everything into a big pot. Now you have to null-check in the callbacks to make sure your things are still alive. Track your own state and you'll be fine. Coroutines will stop when the owner dies and that is by design. Leverage that to ensure brain dead clean up. Objects are very often going to be disabled through user action anyway, eg quitting a level. Its better to just assume that will happen at any time and plan accordingly.
- dleslie 6y agoIn the case of UGC, you have zero ability to assume control of the object's lifecycle and enabled state. Zarro.