StopCoroutine by reference?

Hi! I’m facing logical problem.

I’m using coroutine which loops some object inside its code. Sometime, I can have that object deleted, while coroutine still works.

Insted checking every line in coroutine against null, can I just StopCoroutine when object gets deleted? I can store Coroutine reference, but StopCoroutine function accepts only string name.

Any good solutions to this?

wasn’t there an:
void OnDestroy(){}
and a function StopAllCoroutines();

might work if you just add this to a code file:
void OnDestroy(){
StopAllCoroutines();
}

tohugh i’m not sure if it just stops really all existing coroutines everywhere or just the ones started be the script where this is called.

I see… I’m not sure too, I hope someone from Unity devs will share some light

I still can’t find solution for this problem. Sometimes I just can’t destroy object which called Courotine, but it needs to be stopped from cross-referenced object. Anyone can think of solution?

public void StopSomething() {
    StopCoroutine("SomeCoRoutine");
}

...
// in another script
TheOtherScript otherScript = GetComponent<TheOtherScript>();
otherScript.StopSomething();

P.S. StopCoroutine/StopAllCoroutines only stop the Coroutines in the object where the StopCoroutine is called from. Coroutines are part of MonoBehaviour and each MonoBehaviour manages it’s own Coroutines, that’s why it has to stop them too