How do I reference any instance of a prefab?

Hello! I’ve got a small problem involving one player-controlled character and a lot of bullets.

Every time I get hit by this bullet prefab, I want to have a very short timespan (Done as a coroutine) where I can press “Shift” and save myself.


The code that “Kills” the player is done in the instance of every bullet prefab, its triggered on collision:

    IEnumerator Invincibility()
    {
        yield return new WaitForSeconds(Iframes); //pauses code so you don't die immediately
        if(netCollider.GetComponent<CircleCollider2D>().enabled == true) //checks if shift is pressed
        {
            killItem(); //bullet destroy's itself
            StopCoroutine("Invincibility");
        }
        else
        {
            Debug.Log("You Died!");
        }
    }

This code works, but even when the player presses shift the coroutine must continue executing before stopping, and that looks a little awkward.


I was wondering if there is a way to reference (and terminate) a specific coroutine from the prefab the player collided with? So that I could call for the coroutine to stop from the player Object and have it stop immediately.

I have considered using static variables and update functions in the prefabs, but I don’t have a solid understanding of the first (and it didn’t seem to work well with coroutines) and update functions in every instance of a prefab sounds very taxing. Any help is welcome and let me know if you need elaboration.

Ah, and deleting the prefab works, but messes with some of the code and isn’t a great option, one I’d like to avoid if possible.

In general yes, you can save a reference to a coroutine in a variable.
This can be taken from the >Unity Documentation>

Long story short:

   StartCoroutine(Invincibility());

Can also be written as:

  var myRoutineReference = Invincibility();
  StartCoroutine(myRoutineReference);

In the same manner you can stop a coroutine:

 StopCoroutine(myRoutineReference);

I can in general recommend to go this path if you want to stop a routine as this avoids using strings. Strings are imo a bad way to do this as these are not listed as references to a function and thus can be missed when doing refactoring. It’s also way easier to add typos here.

you can ofc always force a routine to stop by going out of scope of the routine (so basically a normal “function end”) or adding a yield break on a certain point.