Hey
Not sure if anyone will find this useful but its a piece of code to help fade in (or out) GUI.Labels over time.
This is just something I’ve came up with for now, and it’s no doubt not the best implementation but I thought I’d share it as when I was searching for something similar, nothing came up.
Feel free to pick it to pieces, offer suggestions or just tell me there is a better way to do this!
Thanks.
using UnityEngine;
using System.Collections;
public class GUILabelFade : Object {
private float duration = 5F;
private float durCount = 0F;
private string text = "";
private Rect pos;
public bool hasCompleted = false;
//Fade direction, fade in = true
private bool fadeIn = false;
private int min, max;
public GUILabelFade(float dur, string text,Rect pos, bool fadeIn = true)
{
this.hasCompleted = false;
this.duration = dur;
this.text = text;
this.pos = pos;
this.fadeIn = fadeIn;
if(fadeIn)
{
this.durCount = dur;
}
}
public void Render(Color prevColor)
{
if(!hasCompleted)
{
if(this.fadeIn)
{
durCount -= Time.deltaTime;
} else {
durCount += Time.deltaTime;
}
if(durCount < 0)
{
durCount = 0;
} else if(durCount > duration)
{
durCount = duration;
}
GUI.color = new Color(prevColor.r,prevColor.g,prevColor.b,durCount == 0 ? (fadeIn ? 1 : 0) : Mathf.Lerp(1, 0, durCount / duration));
if((GUI.color.a == 1 fadeIn )||(GUI.color.a == 0 !fadeIn ))
{
hasCompleted = true;
}
}
if((!hasCompleted !fadeIn) || (hasCompleted fadeIn) || !hasCompleted)
{
GUI.Label(pos,text);
GUI.color = prevColor;
}
}
}
Usage:
using UnityEngine;
using System.Collections;
public class FadeScript : MonoBehaviour {
private GUILabelFade testFade;
private GUILabelFade testFade2;
// Use this for initialization
void Start () {
testFade = new GUILabelFade(3F, "Test text", new Rect(50,50,100,30), false);
testFade2 = new GUILabelFade(3F, "Tester text", new Rect(150,150,100,30));
}
void OnGUI()
{
testFade.Render(GUI.color);
GUI.color = Color.red;
testFade2.Render(GUI.color);
}
}