Trying to lerp the transparency value of a cube’s mesh renderer from 100% to 0%.
The material is a plain green material made in Unity
The script is on a seperate game object, the cube is referenced as a variable in the script
The material is set as a ‘Transparent/Diffuse’
The material’s alpha value begins at 0
When i press ‘l’, the material goes fully (100%) opaque (this is good)
However, it DOESN’T then lerp fully to 0% (this is bad)
When i look at the printed alpha value in the console, it is ‘flicking’ between 0.95 and 0.94
Can anyone tell me why the value isn’t reducing to 0.0?
Here’s the code:
var damScreen1 : Renderer;
var lerpDuration : float = 1.0;
var lerpNow : boolean = false;
function Update () {
//Displays the transparency value
print (damScreen1.renderer.material.color.a);
if (Input.GetKey ("l"))
{
lerpNow = true;
}
if (lerpNow == true)
{
damScreen1.renderer.material.color.a = Mathf.Lerp(1.0, 0.0, lerpDuration * Time.deltaTime);
}
}
As always, thank you for your time!
Tom
Mathf.Lerp does not animate the property. It gives you a single value.
Mathf.Lerp(1, 0, 0); // returns 1
Mathf.Lerp(1, 0, 1); // returns 0
Mathf.Lerp(1, 0, 0.5f); // returns 0.5
Mathf.Lerp(2, 0, 0.5f); // returns 1
If you want to use Lerp to animate a value you need to use a variable as the third parameter.
var damScreen1 : Renderer;
var lerpDuration : float = 1.0;
var lerpNow : boolean = false;
private var lerpStart : float = 0;
function Update () {
//Displays the transparency value
print (damScreen1.renderer.material.color.a);
if (Input.GetKey ("l")) {
lerpNow = true;
lerpStart = Time.time;
}
if (lerpNow) {
var progress = Time.time - lerpStart;
damScreen1.renderer.material.color.a = Mathf.Lerp(1.0, 0.0, progress / lerpDuration);
if (lerpDuration < progress) {
lerpNow = false;
}
}
}
See also
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
You either need to lerp from current color, or use Time.time as mentioned in previous comment, in your case you lerp from 1 to 0 by time.delta time which let say is 0.033f in 30FPS. so after 1 frame your alpha is 0.967. Than in next frame you lerp again from 1 to 0 so you alpha will remain at this value.
so you either do like in this unity exampe http://docs.unity3d.com/ScriptReference/Color.Lerp.html
or change your code to something like this :
damScreen1.renderer.material.color.a = Mathf.Lerp(damScreen1.renderer.material.color.a, 0.0, lerpDuration * Time.deltaTime);
its not the best use of lerp but will help you understand issue
//edit almost forgot, if i am correct you cannot change alpha directly (you should get an error)
try This solution