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?

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: Unity - Scripting API: WaitForSeconds