This is the function I use:
public IEnumerator fade(GameObject obj,float fadeSpeed = -0.1f){
for (float f = obj.GetComponent<Renderer>().material.color.a; f <= 1 && f>=0; f += 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