I promised some insight into some of the problems Unity presents as a platform for development a while back. There’s no better time to blow off steam discuss those limitations and little land mines than when you’re experiencing one. As some of you might be aware, Unity has support for something called Coroutines for organization of things dependent on order of events, so it shouldn’t be a surprise that we’re utilizing this heavily for our event system.
The pros: You can start these coroutines easily and control the flow just as easily. The StartCoroutine function will take a function from anywhere (like a modular collection of managed event objects that all have different operations like “Walk Over There” and “Pick This Up”), and just fire them off into an autonomous mode. Fire it off and forget it.
The cons: Fire it off and forget it. You can’t stop them easily. There’s only one way to do it, and the implementation (called StopCoroutine, logically enough) is a shabby afterthought. It requires that you use an override of StartCoroutine that (as far as I’m aware) doesn’t support object oriented programming or code reusability, requiring the Coroutine functions you want to fire to be a part of the object doing the firing. The object doing the firing is my Event Manager. The operation needing to be fired is in a separate interface implementation, and for good reason.
Put another way, let’s say I have an Event Management System that handles running all our operations. This is a system separate of the actual implementation of operations. Each type of operation needs it’s own “FireMeOff” function, because they all do different things but there’s no reason for the manager to know what each one needs to do. It should just see the required function is there for the operation and get it running and/or stop it if required to do so. As the Unity team has implemented this, unless every version of “FireMeOff” resides in my Event Manager, there will be no convenient way of stopping the Coroutines that get shot off into digital space.
The apparent solution: Far from elegant … I’ll have to implement the control of my event Coroutines at the operation level, instead of the MANGER level, where it should be. This might include having to edit each operation to include special instruction for flushing out of the Coroutine. Not. Bueno.
The much better solution, which I see no option for: If I were to fire off a Coroutine using StartCoroutine, I would like to be able to store the reference to the Coroutine as the StartCoroutine fires. E.G., Coroutine myCoroutine = StartCoroutine(myFunction());
Ideally, I could then call myCourtine.Stop();