1
\$\begingroup\$

I want to fade out an image, so I have a coroutine FadeOut(). However, I want to have a separate 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?

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

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;
    }
}
\$\endgroup\$
3
  • \$\begingroup\$ So does a coroutine only repeat the while loop inside? Will this code call GetComponent every frame? \$\endgroup\$
    – Impmaster
    Commented Aug 3, 2016 at 10:21
  • \$\begingroup\$ Yes, only the inside of the loop is repeated. \$\endgroup\$
    – Nikaas
    Commented Aug 3, 2016 at 10:40
  • \$\begingroup\$ And therefore, it won't call GetComponent every frame. Please read "A Practical Description of Coroutines for Game Programmers" down here: stackoverflow.com/questions/12932306/… \$\endgroup\$ Commented Aug 3, 2016 at 11:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .