Hi there!
I am creating a simple AI system for my game, and I ran into a weird issue. In my implementation the AI decides every once in a while to take an action (represented by a GameAction object), and I pass that action to a routine to be executed when certain conditions are met. I store the Coroutine object resulting from the StartCoroutine() to avoid the AI overriding an already started action:
void Update () {
if (currentCoroutine != null) { return; }
elapsedTime += Time.deltaTime;
if (elapsedTime >= coroutineCallingPeriod) {
elapsedTime -= coroutineCallingPeriod;
currentCoroutine = StartCoroutine (GameActionCallerRoutine(new ExampleGameAction()));
}
}
private IEnumerator GameActionCallerRoutine(GameAction gameActionToExecute) {
// some irrelevant condition before calling Execute()
gameActionToExecute.Execute();
currentCoroutine = null;
yield return null;
}
The variable currentCoroutine is set to null at the end of GameActionCallerRoutine, however, it does not work! I can notice this by no more actions being called ever again!
Upon further research it turns out that the problem is related to the routine having as a parameter an interface or abstract class (GameAction of which ExampleGameAction is a concrete implementor).
The weirdest part is that if instead of a Coroutine I store the routine before StartCoroutine() into an IEnumerator, then it can be nulled:
// it works this way!
currentCoroutine = GameActionCallerRoutine(null);
StartCoroutine (currentCoroutine);
So I know I already have a solution for this, but can someone explain what’s going on here? I suspect that something stores a reference to the Coroutine object, but why can’t a variable I have complete control over set to be null just because the routine has an abstract parameter?
Thanks!
Harinezumi