How to use corutines in a class

Hi, I’m trying to make a menu class with a fade function. My problem is that I can’t used coroutines in my class, they just don’t work and I don’t get any errors in the console. I want to be able to write something like this:

myMenu.FadeOut();

or

yield myMenu.FadeOut();

I’m not sure, I’ve tried every combination I can think of but nothing.

this is my class:

static class Menu {

	var menu //this is assigned in another part of the class
	
	function FadeOut(){
		while (menu.renderer.material.color.a > 0){
			menu.renderer.material.color.a -= 0.1;
			yield WaitForSeconds(1);
		}
	}
	
	//I have removed the rest of the functionality since it is irrelevant
}

Is there a way I can do this? Any help would be great thanks!

Coroutines can only be run in classes derived from MonoBehaviour. Please copy your function to such class, attach it to your menu (or any other object, where you have menu variable) and then test it.

EDIT: you can have your coroutine defined in static class, but you have to call it from standard class derived from MonoBehaviour. Calling it directly using

Menu.FadeOut()

will not work in your case, but if you explicitly use StartCoroutine, this will work

StartCoroutine(Menu.FadeOut())