Fading OnGUI elements with GUI.color

Hi,

I’m attempting to get some fade in/out affects in OnGui… So far I’ve been working with code from this thread, which is in JS and four years old, so things may have changed.

I’m translating this bit of code from the thread mentioned above:

private var guiAlpha : float;

function Start () {
	yield GUIFade(0, 1, 1); // Start, end, length in seconds
}

function OnGUI () {
	GUI.color.a = guiAlpha;
	if (GUILayout.Button("Click me to fade out")) {
		GUIFade(1, 0, 2);
	}
}

function GUIFade (start : float, end : float, length : float) { 
   for (i = 0.0; i <= 1.0; i += Time.deltaTime*(1/length)) { 
      guiAlpha = Mathf.Lerp(start, end, i); 
      yield; 
   }
   guiAlpha = end; // Accounts for Time.deltaTime variance
}

This is my version in C# (which isn’t working):

        public texture tutBox;
        static float guiAlpha = 0.0f;
	static Color guiColor = new Color(1,1,1,guiAlpha);
	
	void OnGUI(){
		guiColor = new Color(1,1,1,guiAlpha);
		GUI.color = guiColor;
		StartCoroutine(GUIFade(0.0f, 1.0f, 2.0f));
		GUI.Box(new Rect(Screen.width/2, Screen.height/2, tutBox.width, tutBox.height), tutBox);
	}
	
	IEnumerator GUIFade (float start, float end, float length) { 
		print ("fade started");
		for (float i = 0.0f; i <= 1.0f; i += Time.deltaTime*(1/length)) { 
			guiAlpha = Mathf.Lerp(start, end, i); 
			print (guiAlpha);
			yield return new WaitForEndOfFrame(); 
		}
		guiAlpha = end; // Accounts for Time.deltaTime variance
	}

It seems like the guiAlpha Lerp is not happening properly… it jumps all over the place and never ends. Can someone point me in the right direction?

Thanks for the help!

I don’t know if this fits your use or not. Actuly i don’t even know if it works…:slight_smile:
But from the top of my head:

var alpha = 0f;
function OnGUI() {

  if(alpha < 1f)
    alpha = Fade(0f,1f,0.8);

  GUI.color.a = alpha /1;
  GUI.Box(Rect(110,0,100,100),""+alpha /1);
  GUI.color.a = 1;
  GUI.Box(Rect(0,0,100,100),"1");

}

private var fadeStart = 0f;
private var fadeSpeed = 0.8f;
private var fading = false;
function Fade(start : float, end : float, speed : float) {
  if(!fading) {//This if statement is only true the first time the function is called before the fading has ended. If you want to stop a fade before it's done then set fading to false.
    fading = true;
    fadeStart = Time.time;
    fadeSpeed = speed 
  }
  if(start < end) {//If we are fading in.
    var alpha = start + (Time.time - fadeStart) / fadeSpeed;
    if(alpha >= end ) {
      alpha = end;
      fading = false;
    }
  }
  if(end < start) {//If we are fading out.
    var alpha = start - (Time.time - fadeStart) / fadeSpeed;
    if(alpha <= end ) {
      alpha = end;
      fading = false;
    }
  }
  return alpha;//Return the alpha so we can set the GUI's alpha.
}

You could do this in a more consistent manner by using the tweening framework. There’s iTween for example.