Wednesday, June 19, 2013

Unity: Making Meshes Fade Away

To make a model disappear in Unity over time, you lower the alpha of its materials until it reaches zero. ("alpha" is industry speak for transparency. I don't know why.)

The default material does not have an alpha channel, so set up a material that uses the Transparent/Diffuse shader.


For performance reasons, don't use a material with a Transparent/Diffuse shader unless you are fading it out. The GPU must make additional calculations for each pixel with alpha -- even if it's opaque!

Once the mesh has the right material, you can fade it out with this code:

float fadeTimerMax = 1;
float fadeTimer = 1;

void Update () 
{
 // Decrement the timer
 fadeTimer -= Time.deltaTime;

 // If the timer is less than or equal to zero, destroy the object
 if (fadeTimer <= 0)
 {
  Destroy (gameObject);
 }
 // Otherwise, adjust transparency
 else
 {
  // Get a normalized percentage value based on the fade timer
  float percentOpaque = fadeTimer/fadeTimerMax; 

  // Update the alpha of each renderer material on the object
  foreach (Material mat in renderer.materials)
  {
   Color color = mat.color;
   color.a = percentOpaque;
   mat.color = color;
  }
 }
}

1 comment: