- Home /
Question by
Christian.Tucker · May 08, 2015 at 12:34 AM ·
uiimage
Changing opacity through script
Trying to change the opacity of an image to make it fade in and out through a script, here's my code:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class CountdownAnimatedBackground : MonoBehaviour {
public Image Background;
public Color ImageColor;
private bool up = false;
void Start () {
// 31.875 iterations per second
ImageColor = Background.color;
InvokeRepeating("ModifyOpacity", 0f, 0.0313725490196078f);
}
void ModifyOpacity() {
if(ImageColor.a == 0)
up =true;
if(ImageColor.a == 255)
up=false;
if(up)
ImageColor.a = (ImageColor.a + 1);
else
ImageColor.a = (ImageColor.a - 1);
Background.color = ImageColor;
}
}
Whenever it reaches a = 0it quickly flashes 0 opacity then back to full.
We're making the image go from fully visible to not visible in 8 seconds, 31.875 iterations * 8 = 255.
Comment
Answer by WillNode · May 08, 2015 at 01:19 AM
I suggest it will be better to use Coroutines instead.
public class CountdownAnimatedBackground : MonoBehaviour {
public Image Background;
public Color ImageColor;
private bool up = false;
void Start () {
ImageColor = Background.color;
StartCoroutine(ModifyOpacity());
}
IEnumerator ModifyOpacity() {
ImageColor.a=1; //Full Opaque
for(int i = 0; i < 100; j++){
ImageColor.a -= 0.01f;
Background.color=ImageColor;
yield return new WaitForSeconds(0.08f); //Wait
}
return null;
}
}
just a side note, Unity Color isn't ranging from zero to 255, it ranged from zero to one.