Encapsulating Alpha Fade in Unity3d

Friday, November 12th, 2010

Several days into my late Unity3d project I realised that the was a bulk of code designed solely to make an object invisible by fading it out of the scene. The code was not complex although because of the way it was all in one class it appeared complex.

After doing some research into the best way to go about making this change, realised it was both convenient and logical to extract the code into a separate script and attaching that to the object that I wished to apply the effect to.

This meant that instead of nested if-statements for state management in a script attached to the Main Camera I was able to make declarative statements:


I have named the script SmoothAlpha only by my convention no actual smoothing or damping of the alpha value, it is simply a linear reduction of the materials alpha value.

There are many improvements that could be made to the script, some of which I may well do over the coming weeks:

  • Should include a delegate call back to signal when the fade is complete.
  • Should include methods to instantly make an object (in)visible.
  • Should support changing the alpha of child GameObjects in unison with the parent.

In have included the full script below the cut.

Unity3d plus three weeks

Saturday, November 6th, 2010