If fading to invisible is how a GameObject communicates to the player that it is leaving the scene (completed/dying), then we may want that GameObject to be destroyed after the fading process is completed. Let's add this feature to our code.
Do the following:
- Add a new public Boolean variable to our script (default to false):
public bool destroyWhenFadingComplete = true;
- Add a new EndFade() method that sets isFading to false and then tests whether the public destroyWhenFadingComplete variable was set to true and, if so, destroys the GameObject:
private void EndFade() {
isFading = false;
if(destroyWhenFadingComplete)
Destroy (gameObject);
}
- Refactor the FadeAlpha() method so that it invokes EndFade() when the fading is completed (fadeProgress >= fadeDurationSeconds):
private void FadeAlpha()
{
float fadeProgress = Time.time - startTime...