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?