To Coroutine, or Not to Coroutine

I have a design question.

I’ve found a few times I have come across a method which makes sense to have a coroutine and non-coroutine version.

For example, let’s say I have a State class, and that State class has two methods: Activate() and Deactivate(). State.Activate() is called when the State is first enabled, and handles a transition to that state. Similarly, State.Deactivate() is called before a new state is activated.

In some instances, I just want to call State.Deactivate() and leave it at that. But then in other instances, I want to script a sequence, so I’d do something like this instead:

yield return StartCoroutine(OldState.Deactivate());
NewState.Activate();

Without getting into a discussion about better ways to handle State management (LOL!), I’m wondering if anyone has come across this problem of wanting a coroutine and non-coroutine version of a method, and how you handle it when you do?

Do you simply have two version of the method?

void Activate();
void ActivateCoroutine();

Or do you do something much more clever?

I do stupid things like:

enum stateType{fart, sit, idle, punch, whatever}
var state:stateType = stateType.idle;

Then it’s just a switch statement for (state) in the code. That’ll be running regardless forever. I don’t really optimise or make things confusing. I probably should. In general, I just do less if I want it faster.

I think all this Activate and Deactivate is a recipe for sphagetti code.

Leaving aside the whole question of state implementation (I’ve spent many a sleepless night pondering an elegant solution to that issue), I do exactly what you suggest - simply write two versions of the method and call whichever is appropriate.

Unless you specifically need yield, you could start Activate via InvokeRepeating, then you don’t need two separate versions.

http://unity3d.com/support/documentation/ScriptReference/MonoBehaviour.InvokeRepeating.html