- Home /
Question about Coroutines in a Class Function
I'm trying to use a coroutine in a class function. Similar to this:
public class Player{
var health : int = 100;
function Player(){
}
function ApplyBuff(spell : Spell){
health += spell.spellAmount;
yield WaitForSeconds(spell.spellDuration);
RemoveBuff(spell);
}
function RemoveBuff(spell : Spell){
health -= spell.spellAmount;
}
}
What this is doing is applying a spell buff to the player, then after the duration of the buff, it removes it. If I do this in a regular script, it seems to work fine. If i remove the yield statement in the class function, it adds the buff like expected. But if I add the yield, the class function doesn't fire at all.
Can you just not use a coroutine in a class function? Does it have to be a MonoBehavior? As for the documentation on coroutines, it seems it states the only places you can't use it are in the Update() and FixedUpate() functions. But it doesn't implicitly state it can only be used in a MonoBehavior.
Note, this is not my entire class, but is a representation of the problem I am having.
Answer by darthbator · Jun 04, 2013 at 04:46 PM
I'm maybe not the best person to answer this from a technical standpoint but you are correct. In order to implement a unity coroutine I believe your class needs to extend monogame.
I don't do JS but to the best of my knowledge neither JS nor C# have a native concept of a "coroutine". In C# you sort of fake it with iterators which is why coroutines are declared *IEnumerator methodName ()*in C#.
I guess that means that the yield function is a function of the monobehavior class? I guess that makes sense why I can't use it. You would think it would give me an error of some description, rather than just not executing at all.