- Home /
Fading Canvas Group
I've got a piece of code I adapted from another thread to fade an entire canvas in and out, however when I run the code the canvas completely disappears instead of slowly fading. The code is as follows:
private IEnumerator FadeCanvas(GameObject canvas, float target){
float startTime = Time.time;
float endTime = startTime + transitionDuration;
float elapsedTime = 0f;
float percentage;
float initialAlpha = canvas.GetComponent<CanvasGroup>().alpha;
while(Time.time < endTime){
elapsedTime = Time.time - startTime;
percentage = 1 / (transitionDuration / elapsedTime);
if(initialAlpha > target){
canvas.GetComponent<CanvasGroup>().alpha = initialAlpha - percentage;
canvas.SetActive(false);
}
else {
canvas.GetComponent<CanvasGroup>().alpha = initialAlpha + percentage;
canvas.SetActive(true);
}
yield return null;
}
}
And is called from the following function:
private IEnumerator startGame(){
cameraScript.Game();
yield return StartCoroutine(FadeCanvas(mainMenu, 0f));
mainMenu.SetActive(false);
inGameScreen = true;
}
Is there something I'm not seeing here?
Answer by ChrisKurhan · Dec 12, 2017 at 11:32 PM
I would recommend using an Animator + Animation to make your canvas fade in/out and just do Animator.Play("yourFadeOutAnimationName");
. The alpha is available on the timeline for the CanvasGroup.
However if you do want to do it in code as your question says, your FadeCanvas
Coroutine does not ever wait during the execution. Change your yield return null
to yield return new WaitForSeconds(delay);
and set up a delay variable on your class that specifies how long in seconds to wait for. Keep in mind you will likely need to adjust your while loop condition to something like while(canvasGroup.alpha > 0)
or < 1
when fading in/out in this way [SerializeField][Range(0.001f, 1f)] private float delay;
as a class variable for example.
Documentation link: https://docs.unity3d.com/ScriptReference/WaitForSeconds.html
[SerializeField][Range(0.001f, 1f)] private float delay;
I don't understand this part, does it create a float with a random value?
No, this allows you to set it in the inspector.
Lower values will have higher cpu utilization but be smoother, while higher values will use less cpu utilization and be more noticeable on the steps.
60 fps is like .0167 if you want to start with that and see. You should play with both this number and your percentage
number to find a smooth looking setup
Your answer
Follow this Question
Related Questions
Fadeout Issue 0 Answers
Audio won't fade out. 1 Answer
Changing alpha value of a canvas from a different game object 1 Answer
Add on click event to canvas button 1 Answer