- Home /
Cannot call Coroutine on another Gameobject.
I tried to call a coroutine from an instance of my enemy. But when I log the called IEnumerator function from the Enemy object, it return "this.gameObject" as my Player object.
// This is the function called from my Player instance of "Character" class
void Launch(GameObject wpn)
{
// I Called the enemy coroutine
BattleManager.instance.enemy.GetComponent<Character>().StartCoroutine(CharacterHitted(targetId,delayTime));
}
// And this is the IEnumerator from same class.
public IEnumerator CharacterHitted(int partsIdx, float delayTime)
{
yield return new WaitForSeconds(delayTime);
Debug.Log("THIS : "+this.gameObject); // returning my player GameObject
}
I want the "this" returning the Enemy instance. Maybe you have another trick to call function with arguments with delay?
Answer by musaranya · May 09, 2014 at 06:52 AM
I think StartCoroutine(x) looks and triggers a function x in the same script. To call a coroutine from another script you can do something like this
http://answers.unity3d.com/questions/131210/c-how-to-make-a-script-talk-to-a-coroutine-in-anot.html
@musaranya Oh I see, that this behavior is normal for StartCoroutine. I thought we can call it from another object instances. It is a little bit messy to have an empty function that only call a Coroutine. Thanks for the answer
Answer by Maerig · May 09, 2014 at 06:59 AM
Something like this, maybe ?
private delegate void Callback(GameObject gameObject);
public void MethodWhichUsesTheGameObject(GameObject gameObject) {
// Your code
}
void Launch(GameObject wpn)
{
BattleManager.instance.enemy.GetComponent<Character>().StartCoroutine(CharacterHitted(targetId,delayTime, MethodWhichUsesTheGameObject));
}
private IEnumerator CharacterHitted(int partsIdx, float delayTime, Callback callback)
{
yield return new WaitForSeconds(delayTime);
callback(gameObject);
}