- Home /
 
Coroutine cannot be automatically started from a static function
So I have a static (!!) function which does something great, at the end of this function I want to call another function with a coroutine in it (called fadeOut()), what happens now is that the coroutine doesn't start and unity gives me the following warning:
WARNING: Coroutine 'fadeOut' cannot be automatically started from a static function.
I have no idea what to do now.. the internet tells me I have to put the coroutine in another script but this doesn't work aswell, gives me the same warning and same effect!
My Code:
 static function myStaticFunction(){
     [...some code...]
     fadeOut(0.5);
 }
 
 static function fadeOut(duration : int){
     for(var t = 0; t < duration*100; t++)
     {
         [...some code...]
         yield WaitForSeconds(0.01);
     }
     return;
 }
 
               Well.. help :D Probably I'm just not understanding or seeing somethign very easy, but I don't quite know what at the moment and please don't just say like "put fadeOut in another script", please explain me how exactly or better why as I didn't get it when the others explained it :o
PS: I'm a 15 year old german student, so my english isn't the best (and my understanding aswell) :)
Answer by amanpu · Nov 06, 2015 at 07:54 AM
Yes you can invoke Coroutine from static method for that you need instance of class. Following code examples will explain it better than me. 
 C# :
 public class CoRoutineTest : MonoBehaviour {
 
     private static CoRoutineTest instance;
 
 
     void Start()
     {
         instance = this;
         StaticStart();
     }
 
     static void StaticStart()
     {
         instance.StartCoroutine (instance.FadeOut());
     }
 
     IEnumerator FadeOut()
     {
         yield return new WaitForSeconds (1f);
         Debug.Log ("Ohh Someone call me");
     }
 }
 
               UnityScript :
 public class CoRoutineTestJS extends MonoBehaviour {
 
     private static var instance: CoRoutineTestJS;
 
 
     private function Start()
     {
         instance = this;
         StaticStart();
     }
 
     private static function StaticStart()
     {
         instance.StartCoroutine (instance.FadeOut());
     }
 
     private function FadeOut(): IEnumerator
     {
         yield  WaitForSeconds (1);
         Debug.Log ("Someone call me too :)");
     }
 }
 
               Thanks to C# to UnityScript Converter
Your answer
 
             Follow this Question
Related Questions
Static and Coroutines help 2 Answers
StartCoroutine important for using yield? 1 Answer
Function can't be called 0 Answers
Fading sprite's alpha via coroutine 1 Answer
call a function of another object 2 Answers