How can I get seperate caches for different coroutines? (Unity)

by Impmaster   Last Updated August 03, 2016 08:05 AM

I want to fade out an image, so I have a coroutine FadeOut(); However, I want to have a seperate image each time I call FadeOut.

If I try to do something like this:

IEnumerator FadeOut(GameObject image) {
    SpriteRenderer render = image.GetComponent<SpriteRenderer>();
    yield return null;
}

Ignoring all the color changing code which I took out, how do I make it so that I can save a separate cache for each image I add? I don't want to run GetComponent() each frame, because I'm running on mobile and because I want to think of a clever way to stash the renderer.

For example, if I declare the renderer at the top like this:

private SpriteRenderer render;

and want to cache it on the first frame of the coroutine, there's the chance that calling FadeOut() on another object will change the renderer to a new object and the first FadeOut() will cancel.

Can I make the method static? Will that cache a private version of renderer?

Tags : unity coroutines


Answers 1


The code that you provided should already be doing what you are asking. If I call StartCoroutine(FadeOut(image1)); and StartCoroutine(FadeOut(image2));, the two coroutines have their own separate SpriteRenderer renderer; local references. Unity does not confuse the two. You can continue to fade out image1 even though image2 also started to fade out. That local renderer is the renderer specifically for the image that you started the coroutine with.

So, this kind of a code will work just fine. Inside the while loop, renderer is the renderer of the image that you initiated this call to the coroutine. You can have many such calls, for every new call, you have a separate local renderer variable. They don't affect each other.

IEnumerator FadeOut(GameObject image) {
    SpriteRenderer render = image.GetComponent<SpriteRenderer>();
    while(!renderer.isDone) {
        renderer.FadeOutOneMoreStep();
        yield return null;
    }
}
Gazi Alankus
Gazi Alankus
August 03, 2016 10:17 AM

Related Questions





NullReferenceException in StartCoroutine method

Updated November 25, 2016 08:05 AM

Best way to queue animation coroutines in unity

Updated April 15, 2017 00:13 AM