- Home /
Fading Not Working
Hi all, I don't know why but the fading that I'm using doesn't really seem to work. The fade doesn't start when the object is created, it starts at the beginning and takes for ever to fade after it has been Instantiated. Anyone have any ideas? Here's the code:
using UnityEngine;
using System.Collections;
public class Fade : MonoBehaviour
{
Color startColor;
Color currentColor;
Color endColor;
bool shouldFade = false;
float startTime;
float endTime;
public float seconds = 5.0f;
float t;
void Start ()
{
startColor = gameObject.renderer.material.color;
endColor = new Color(startColor.r, startColor.g, startColor.b, 0.0f);
}
void Update ()
{
shouldFade = true;
startTime = Time.time;
endTime = startTime + seconds;
fade();
}
void fade()
{
if ( shouldFade == true)
{
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;
Destroy (gameObject);
}
}
}
}
Answer by KurtGokhan · Jan 12, 2015 at 01:44 PM
If you are using startTime and endTime in your fade() function, I think you should move setting them into Start(). I dont know fade() code but I guess you are using current time to inverse lerp between startTime and endTime and apply lerp to color. As it is, current time and startTime is almost same.
That worked mate! When I come to think about it it was kind of a stupid mistake I made... Well, at least I now know the answer. Thanks a ton.