Created
August 28, 2014 20:25
-
-
Save nbrew/c662dbdddb8310af6f2a to your computer and use it in GitHub Desktop.
Unity 3D FadeTest - Fade object alpha over time.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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