- Home /
renderer.material.color not being changed?
Hey guys, I got a pretty simple problem to solve, but I'm not sure what I'm doing wrong.
I am trying to make an object "fade out" based on distance. These objects are being rendered on their own camera, and will be clipped out at a certain distance, however its pretty jarring without any fading. My plan is to Lerp their color from gray to black (they are set to Additive, so black = transparent) just before they are clipped. This way, they will appear to "fade out."
However, my code doesn't produce any results.
Here is my code:
{
public Transform camR;
// Update is called once per frame
void Update ()
{
float dist = Vector3.Distance(camR.position, transform.position);
print ("Distance to CamR:" + dist);
if(dist >= 20.0f)
{
renderer.material.color = Color.Lerp(Color.grey, Color.black, Time.deltaTime);
}
else if (dist <20.0f)
{
renderer.material.color = Color.Lerp(Color.black, Color.grey, Time.deltaTime);
}
}
}
Any help is greatly appreciated :)
Answer by yogee · Nov 23, 2013 at 04:29 AM
try this
var duration = 5.0;
void Update ()
{
var t : float = Mathf.InverseLerp (0, duration, Time.time);
float dist = Vector3.Distance(camR.position, transform.position);
if(dist >= 20.0f)
{
renderer.material.color = Color.Lerp(Color.grey, Color.black, t);
}
else if (dist <20.0f)
{
renderer.material.color = Color.Lerp(Color.black, Color.grey,t);
}
}
Answer by Eric5h5 · Nov 22, 2013 at 05:05 AM
The third parameter in Lerp is a float between 0 and 1. It's like a percentage. Time.deltaTime will normally be a very small number, so your code will pretty much always return a color near Color.grey (in the first Lerp) or Color.black (in the second Lerp). I would suggest using a percentage based on distance rather than Time.deltaTime.
Hey Eric5h5,
Thanks for the reply. I replaced time.deltatime with 0.7f to see if there was a change. Unfortunately, nothing changed.
Is there a better way to get an additive material to change color over time?
I suggested using a percentage based on distance; 0.7 is just a constant and naturally wouldn't do anything except return a value 70% of the way between grey and black.
What's a way to express that? dist / X ?
Sorry about my lack of knowledge here. I'm primarily a game artist and trying to figure a lot of this out as I go :p I appreciate the help.
One way is to use $$anonymous$$athf.InverseLerp to get a 0-1 value from the distance. Something like that:
float t = $$anonymous$$athf.InverseLerp(15, 20, dist);
renderer.material.color = Color.Lerp(Color.grey, Color.black, t);
this would set the color to grey if dist is between 0 and 15, it would lerp from grey to black between 15 and 20 and stay black if the distance is greater than 20.
btw, you don't need the if statements in this case. This fully covers it ;)