Reusable Fade Function for Unity

Posted on

in

,

This is the function I use:

public IEnumerator fade(GameObject obj,float fadeSpeed = -0.1f){
        for (float f = obj.GetComponent<Renderer>().material.color.af <= 1 && f>=0f += fadeSpeed) {

            Color c = obj.GetComponent<Renderer>().material.color;
            c.a = c.a + fadeSpeed;
            if(c.a <0){
                c.a = 0;
            }
            if(c.a >1){
                c.a = 1;
            }
            obj.GetComponent<Renderer>().material.color = c;
            yield return null;
        }
    }

This function has 2 parameters: 1) the game object that’s to be faded and 2) the fade amount. By default it’s -0.1f which you can change. To use this function just use:

StartCoroutine(fade(myGameObject));
StartCoroutine(fade(myGameObject,0.1f));

The first line fades out the object using the default fade value and the 2nd fade it back in at the same speed. The good thing about this function besides being usable is it only runs as many times as needed and doesn’t have to go into the update() area.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

February 2025
M T W T F S S
 12
3456789
10111213141516
17181920212223
2425262728