- Home /
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!
Answer by ArkaneX · Nov 26, 2013 at 02:57 PM
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())
When adding the script to an object I get an error:
Can't add script behaviour $$anonymous$$enu.
The script class can't be abstract.
I'm not really declaring it, just calling it like this:
menu.FadeOut();
I wanted it that way so I could access it easily from any script. This works for me with other classes that havent needed coroutines.
Oh great that is perfect just what I was looking for thanks!!
Your answer
Follow this Question
Related Questions
Question about Coroutines in a Class Function 1 Answer
Reading and Storing External Data into Memory (From Text) 1 Answer
Referencing subclass in Unity JS 2 Answers
Creation of RPG Class Stat Presets? 1 Answer
How to add javascript classes? 1 Answer