- Home /
Fading out doesn't fade out, but instantly goes from black to clear
Hi, so i'm trying to get a fading out effect, but as I have it now it doesn't fade, but instead it instantly goes from black to clear after a certain period of time.
Here is my code:
public float fadeSpeed = 5;
private Material mat;
public float alpha = 255f;
// Use this for initialization
void Start () {
mat = gameObject.renderer.material;
}
// Update is called once per frame
void Update () {
if (alpha > 0)
alpha -= fadeSpeed*(float)Time.deltaTime;
else if (alpha < 0)
alpha = 0;
mat.color = new Color (0, 0, 0, alpha);
}
So I have this script attached to a plane which is placed in front of the camera. The alpha variable is only public so i can see it in the editor for now, and it does decrease like it's supposed to. But the plane doesn't get any clearer, not until the alpha is 0 it instantly changes but doesn't fade. can anyone tell me what's wrong here? The plane's material is Transparent/diffuse in case that matters.
Any help is appreciated, thanks.
The transparent diffuse shader. If I manually drag the alpha bar in the editor it fades away properly, so I dont believe its the shader.
The 'Color' class isn't based on values of 0-255, it's based on a float of 0f-1f
http://docs.unity3d.com/Documentation/ScriptReference/Color.html
The reason it fades instantly is because from 255-1 it's fully opaque, then from 1 to 0 it fades (almost instantly).
Try changing the relevant line to: public float alpha = 1f; and either greatly reduce fadeSpeed or divide it by 255 if you want it to keep its current magnitude.
Oh you know what you're probably right. I ran in to this same problem a while back as well, hopefully this time I'll remember for for the future. I'll fix this tomorrow, im sure thats the problem, thanks. Although, is there not some alternative color class that does utilize the 255 system? If I recall correctly thats what I ended up doing last time.
Anyways thanks, I'll try it out tomorrow and if it works I'll let you know, and you can post your comment as an answer.
@pickle chips, Both OpenGL and DirectX work with floating point color values. Not only are they more accurate than 8 bit color values, but they are much easier to mix and do awesome stuff with. There is no reason Unity should make such a class, but you're welcome to make your own of course ;)
Add to that, you are using deltaTime with a speed of 5:
alpha -= fadeSpeed*(float)Time.deltaTime;
which means your whole fading is done in 0.2s which is not invisible but fairly fast.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Fading all but single instance of a button 1 Answer
Fading out a transparent material 1 Answer
Fading Objects does not work (Unity 5) 0 Answers