< Back to Game Dev, Unity

Reusable Fade Function for Unity

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.

 

Be Sociable, Share!

Leave a Reply

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