- Home /
My fade coroutine won't work without an empty OnGUI method.
Hi everyone,
I noticed something interesting today. I couldn't figure out why my fade coroutine would sometimes work and sometimes not.
My FadeControl.cs is subscribed to a state change event, and fires off a coroutine when the state changes. Interestingly, the fade is aligned to the center of the screen instead of the corner of the screen if I do not include an empty "void OnGUI(){}" at the end of my cs file.
Subscribe to Event on Enable:
private void OnEnable()
{
StateManager.StateChanged += DoFade;
}
Execute Coroutine:
private void DoFade(SceneState e)
{
StartCoroutine(FullFade());
}
Do Fade:
private IEnumerator FullFade()
{
float elapsedTime = 0.0f;
while (elapsedTime < fadeTime)
{
yield return new WaitForEndOfFrame();
elapsedTime += Time.deltaTime;
Color newColor = GUI.color;
newColor.a = Mathf.Clamp01(elapsedTime / fadeTime);
GUI.color = newColor;
GUI.depth = drawDepth;
GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), fadeTexture);
}
elapsedTime = 0.0f;
while (elapsedTime < fadeTime)
{
yield return new WaitForEndOfFrame();
elapsedTime += Time.deltaTime;
Color newColor = GUI.color;
newColor.a = 1.0f - Mathf.Clamp01(elapsedTime / fadeTime);
GUI.color = newColor;
GUI.depth = drawDepth;
GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), fadeTexture);
}
}
Again, this does not cover the whole screen unless I include the following at the end of my script. (Completely empty function:)
private void OnGUI(){}
As it turns out, this is related to a larger problem. This has since been refactored, but the empty OnGUI function is necessary because it tricks the editor into thinking all those GUI calls are actually happening in OnGUI. They are not.
This becomes problematic when making a build (as I just found out) since all those lines that start with "GUI" must be executed in OnGUI in the build. I'm about to post a question related to it.
Answer by Lili-Shi · Jun 14, 2017 at 07:17 PM
Do I see it right, that you try to fade a color? Why don't you use UI.Graphic.CrossFadeColor(Color targetColor, float duration, bool IgnoreTimeScale, bool useAlpha)
?
Your answer
Follow this Question
Related Questions
Fade logo before main menu 2 Answers
Fading an image drawn with GUI.DrawTexture 1 Answer
Disable component via script 1 Answer
How to fade in onGUI on trigger enter/exit? Gui shows on trigger, but no fade. 1 Answer
Fade in from black 4 Answers