Question by
soydrp · Jan 25, 2016 at 11:25 AM ·
c#renderermaterial coloronmouseenteronmouseexit
Color transtition not rendering
Hi - I'm trying to trigger and smooth color transition when I hover on a cube, and back to the original color when exiting. You'll find the code below: it does change the color but ignores the LERP (the intermediate colors). What's more strange is that the renderer.material.color is properly updated with all lerped values(proven by the debug log), but just not rendered on screen (only until the last value). Not sure what Im missing.
public Color colorOn; //change in inspector
public Color colorOff;//change in inspector
public float duration; //secs for the transition - change in inpector
float t = 1;
bool turnOn;
bool turnOff;
private Renderer therenderer;
void Start()
{
therenderer = GetComponent<Renderer>();
therenderer.material.color = colorOff;
}
void OnMouseEnter()
{
turnOn= true;
turnOff = false;
Debug.Log("Trun ON!!)");
turnItOn();
}
void OnMouseExit()
{
turnOn = false;
turnOff = true;
Debug.Log("Trun OFF!!)");
turnItOff();
}
void turnItOn() {
while (t > 0 && turnOn)
{
therenderer.material.color = Color.Lerp(colorOff, colorOn, t);
t -= Time.deltaTime / duration;
Debug.Log(therenderer.material.color.ToString());
}
t = 1;
turnOn = false;
}
void turnItOff()
{
while (t > 0 && turnOff)
{
therenderer.material.color = Color.Lerp(colorOn, colorOff, t);
t -= Time.deltaTime / duration;
Debug.Log(therenderer.material.color.ToString());
}
t = 1;
turnOff = false;
}
}
Thanks!
Comment
Best Answer
Answer by soydrp · Feb 03, 2016 at 09:15 PM
I figured it out:
using UnityEngine;
using System.Collections;
public class ChangeBarWhenHover : MonoBehaviour {
Color colorOn = Color.gray;
Color colorOff = Color.white;
float duration = 0.6f;
float t;
bool turnOn;
bool turnOff;
private Renderer renderer;
void Start()
{
GetComponent<Renderer>().material.color = colorOff;
renderer = GetComponent<Renderer>();
//normal = Shader.Find("Standard");
//hover = Shader.Find("FX/Gem");
}
void OnMouseEnter()
{
turnOn= true;
turnOff = false;
t = duration;
StartCoroutine (turnItOn());
// GetComponent<Renderer>().material.color = Color.gray;
}
void OnMouseExit()
{
turnOn = false;
turnOff = true;
t = duration;
StartCoroutine (turnItOff());
//GetComponent<Renderer>().material.color = Color.white;
}
IEnumerator turnItOn() {
while (t > 0 && turnOn)
{
//print(t + " Fade in" + " Fade out");
renderer.material.color = Color.Lerp(colorOn, colorOff, t);
t -= Time.deltaTime / duration;
//Debug.Log("Color oning: " + renderer.material.color);
yield return 0;
}
turnOn = false;
}
IEnumerator turnItOff()
{
while (t > 0 && turnOff)
{
//print(t + " Fade in" + " Fade out");
renderer.material.color = Color.Lerp(colorOff, colorOn, t);
t -= Time.deltaTime / duration;
//Debug.Log("Color offing: " + renderer.material.color);
yield return 0;
}
turnOff = false;
}
}