Hey guys, I’m trying to make a material slowly changes it opacity. It’s not working well because I only see my material when it’s totally opaque or totally transparent(I can’t see the fade effect) . Here’s the code. Can someone tell me what I’m doing wrong?
using UnityEngine;
using System.Collections;
public class alphaControl : MonoBehaviour {
void Update () {
if(Input.GetKeyUp(KeyCode.T)) {
ToAlpha();
}
if(Input.GetKeyUp(KeyCode.F)) {
fromAlpha();
}
}
void ToAlpha () {
float alpha = transform.renderer.material.color.a;
while(alpha > 0) {
alpha -= Time.deltaTime;
print (alpha);
Color newColor = new Color(1, 1, 1, alpha);
transform.renderer.material.color = newColor;
}
}
void fromAlpha () {
float alpha = transform.renderer.material.color.a;
while(alpha < 1) {
alpha += Time.deltaTime;
print (alpha);
Color newColor = new Color(1, 1, 1, alpha);
transform.renderer.material.color = newColor;
}
}
}
Any help would be appreciated!
Thanks from now.
Guto
what was delta for?
– MD_Reptile@MDReptile: My bad ;) The first solution used this value to determine the "direction" needed to get from the current value to the target value. With the Lerp solution it's not needed anymore. I will remove it, thanks for the hint ;)
– Bunny83Shouldn't transform.renderer.material.color = newColor; be transform.renderer.material.color.a = newColor.a; ? Otherwise the RGB values get set to 1,1,1 and the original colour gets killed.
– Partomojust a note, I noticed that the coroutine returning null will cause it to get out of sync at times.. instead, replace with "yield return new WaitForEndOfFrame();" to fix a strobe effect that may occur. I think that shows up when you have many items that may be running the coroutine... in my case, I had ~20 objects with large textures (0.7 MB) covering quite a bit of screen space. this fixed the issue.
– tswalkfor some reason this doesnt run on me as fading. its like it is doing the calculations in the for loop too fast and the presented result is like the image pops up. if i try to add 10 seconds of time duration it freezes and when unfreezes its finished.(i use js) for (var t: float = 0.0; t < 1.0; t += Time.deltaTime / 10){ var newColor: Color = image.color; newColor.a = Mathf.Lerp(0,1,t); image.color = newColor; }
– Iraklisss