- Home /
Lerp a light intensity gradually to 0
I used this code until now to make a light dim to zero and back to 3 on the same button press. Now it does not stay at 0 but repeats the coroutine on every press. I know there is a better way to do this but haven't figured it out yet.
public Light light;
bool y;
IEnumerator ScaleX1(float start, float end, float time)
{
float lastTime = Time.realtimeSinceStartup;
float timer = 0.0f;
while (timer < time)
{
light.intensity = Mathf.Lerp(start, end, timer / time);
timer += (Time.realtimeSinceStartup - lastTime);
lastTime = Time.realtimeSinceStartup;
yield return null;
}
light.intensity = end;
}
void Start() // =====START====
{
y = true;
}
void Update() // ====UPDATE=====
{
if (Input.GetKeyDown(KeyCode.Q) && y == true)
{
StartCoroutine(ScaleX1(3.0f, 0.0f, 0.25f));
y = false;
}
if (Input.GetKeyDown(KeyCode.Q) && y == false)
{
StartCoroutine(ScaleX1(0.0f, 3.0f, 0.25f));
y = true;
}
print(y);
}
}
Comment
Best Answer
Answer by nullgobz · Aug 09, 2015 at 04:11 PM
Make it an else-if
void Update() // ====UPDATE=====
{
if (Input.GetKeyDown(KeyCode.Q) && y == true)
{
StartCoroutine(ScaleX1(3.0f, 0.0f, 0.25f));
y = false;
}
else if (Input.GetKeyDown(KeyCode.Q) && y == false)
{
StartCoroutine(ScaleX1(0.0f, 3.0f, 0.25f));
y = true;
}
print(y);
}