- Home /
How to stop a coroutine started in Script A from within Script B
Every pickup in my game inherits this method from my base pickup class:
public abstract IEnumerator SpawnPickup(bool PlayPickUpSound);
When implemented, it means that every pickup has a method that goes something like:
public override IEnumerator SpawnPickup(bool PlayPickUpSound)
{
if(PlayPickUpSound == true)
MyAudioSource.PlayOneShot (PickUpSound, 3);
moving = 0;
WaitTime = Random.Range (MinWaitTime, MaxWaitTime);
//some more code here...
yield return new WaitForSeconds(WaitTime);
moving = 1;
}
The problem is if the player dies while a pickup, say, a coin magnet, is still active, then the magnet is permanently active when the player chooses to go for another run (yes, it's the cliche endless runner). I can't call StopAllCoroutines or StopCoroutine in my player's ResetGame function. It seems I can only call those functions within any block of code that contains a StartCoroutine call. I've played different tricks but I can't find a way around it.
Answer by taxvi · Feb 02, 2015 at 07:34 AM
you can implement a custom public function in the pickup class to stop the coroutine.
public void StopLocalCoroutine(){
StopCoroutine("SpawnPickup");
}
then call this function from the outside
I've tried that before. Other scripts won't be able to access the StopLocalCoroutine unless I make it a static variable. And if I make it static, I get this error: Assets/Scripts/Pickups.cs(24,17): error CS0120: An object reference is required to access non-static member `UnityEngine.$$anonymous$$onoBehaviour.StopCoroutine(string)'
all right then. $$anonymous$$aybe you can mark the character dead in playerPrefs?
PlayerPrefs.SetInt("CharacterDead", 1);
then in your SpawnPickup check that PlayerPref and if 0 make it stop itself?