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.GetComponent<Renderer> ().material.color;
endColor = new Color (startColor.r, startColor.g, startColor.b, 0.0f);
}
void Update ()
{
if(Input.GetKeyDown("w"))
{
shouldFade = true;
startTime = Time.time;
endTime = startTime + seconds;
Fade();
}
}
void Fade()
{
while ( shouldFade )
{
t = Time.time / endTime;
currentColor = Color.Lerp(startColor, endColor, t);
gameObject.GetComponent<Renderer>().material.SetColor("_Color", currentColor);
if ( currentColor == endColor )
{
shouldFade = false;
startTime = 0.0f;
endTime = 0.0f;
t= 0.0f;
}
}
}
}
So, i´m trying to fade a gameObject over time, I already had this but unity crash when I execute the script; if anyone have any idea about it please help u.u
Your fade function locks into an infinite loop. I’m guessing that you’re counting on Time.time to increase as this function is looping, but the Time.time value is the time at the start of the frame. Unity - Scripting API: Time.time
The Lerp function requires the first parameter to be something that is changing. Even the function param is labeled ‘from’ and ‘to’. You need to update the Lerp function or else it will just stay the same locked in a certain value.
This gives the Lerp function an updated currentColor which is what you want. I also reccomend you DON’T use GetComponent every frame. It’s an expensive function call and should be used in Awake in order to cache the reference.