Skip to content

Instantly share code, notes, and snippets.

@nbrew
Created August 28, 2014 20:25
Show Gist options
  • Save nbrew/c662dbdddb8310af6f2a to your computer and use it in GitHub Desktop.
Save nbrew/c662dbdddb8310af6f2a to your computer and use it in GitHub Desktop.
Unity 3D FadeTest - Fade object alpha over time.
using UnityEngine;
using System.Collections;
public class FadeTest : MonoBehaviour
{
Color startColor;
Color currentColor;
Color endColor;
bool shouldFade = false;
float startTime;
float endTime;
public float seconds = 5.0f;
float t;
// Use this for initialization
void Start ()
{
Debug.Log ("FadeTest used by " + gameObject.name);
startColor = gameObject.renderer.material.color;
endColor = new Color(startColor.r, startColor.g, startColor.b, 0.0f);
int childCount = transform.childCount;
for ( int childIndex = 0; childIndex < childCount; childIndex++)
{
Transform child = gameObject.transform.GetChild(childIndex);
if (child.gameObject.renderer) {
child.gameObject.AddComponent<FadeTest>();
}
}
}
// Update is called once per frame
void Update ()
{
if(Input.GetKeyUp(KeyCode.F))
{
shouldFade = true;
startTime = Time.time;
endTime = startTime + seconds;
}
Fade();
}
void Fade()
{
if ( shouldFade )
{
t = Time.time / endTime;
currentColor = Color.Lerp(startColor, endColor, t);
gameObject.renderer.material.SetColor("_Color", currentColor);
if ( currentColor == endColor )
{
shouldFade = false;
startTime = 0.0f;
endTime = 0.0f;
t= 0.0f;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment