In this recipe, we will create an object that, once clicked, fades out and disappears. However, the script will be flexible enough to allow us adjust the initial and final alpha values. Plus, we will have the option of making the object self-destructible when turned invisible.
Follow these steps:
Fade_MAT
.FadeMaterial
and open it in your editor.using UnityEngine; using System.Collections; public class FadeMaterial : MonoBehaviour { public float fadeDuration = 1.0f; public bool useMaterialAlpha = false; public float alphaStart = 1.0f; public float alphaEnd = 0.0f; public bool destroyInvisibleObject = true; private bool isFading = false; private float alphaDiff; private float startTime; private Renderer rend; private Color fadeColor; void Start () { rend = GetComponent<Renderer>(); fadeColor = rend.material.color; if (!useMaterialAlpha) { fadeColor.a = alphaStart; } else { alphaStart = fadeColor.a; } rend.material.color = fadeColor; alphaDiff = alphaStart - alphaEnd; } void Update () { if(isFading){ var elapsedTime = Time.time - startTime; if(elapsedTime <= fadeDuration){ var fadeProgress = elapsedTime / fadeDuration; var alphaChange = fadeProgress * alphaDiff; fadeColor.a = alphaStart - alphaChange; rend.material.color = fadeColor; } else { fadeColor.a = alphaEnd; rend.material.color = fadeColor; if(destroyInvisibleObject) Destroy (gameObject); isFading = false; } } } void OnMouseUp(){ FadeAlpha(); } public void FadeAlpha(){ isFading = true; startTime = Time.time; } }
Since the opaqueness of the material using a transparent Shader is determined by the alpha value of its main color, all we need to do in order to fade it is changing that value over a given amount of time. This transformation is expressed, in our script, on the following lines of code:
var fadeProgress = elapsedTime / fadeDuration; var alphaChange = fadeProgress * alphaDiff; fadeColor.a = alphaStart - alphaChange; rend.material.color = fadeColor;
You could call the FadeAlpha
function in other circumstances (such as a Rigidbody
collision, for instance). In fact, you could even call it from another Game Object's script by using the GetComponent
command. The script would be something like:
GameObject.Find("Sphere").GetComponent<FadeMaterial>().FadeAlpha();
18.218.2.231