How to start coroutine from another script?

Did my search and didn’t quite find an answer.
I’m making a countdown timer. Now - it works very neatly if I use start, update and IEnumerator and attach the entire script to the main camera. But I’d like to be able to have the ability to just have a simple call of the timer in another script. Something like Timer.Start_CountDown();

public static IEnumerator Counter(){
	
	for(int a = 9; a >= 0; a--){
		if(a == 9){
			for(int x = 0; x <= 9; x++){
					Ones_Number[x].GetComponent<SpriteRenderer>().enabled = false;
					Tens_Number[x].GetComponent<SpriteRenderer>().enabled = false;
				}
			Ones_Number[0].GetComponent<SpriteRenderer>().enabled = true;
			Tens_Number[9].GetComponent<SpriteRenderer>().enabled = true;
			yield return new WaitForSeconds (1f);
		}
		else
		{for(int i = 9; i >= 0; i--){
			for(int x = 0; x <= 9; x++){
					Ones_Number[x].GetComponent<SpriteRenderer>().enabled = false;
					Tens_Number[x].GetComponent<SpriteRenderer>().enabled = false;
				}
				Ones_Number*.GetComponent<SpriteRenderer>().enabled = true;*
  •  		Tens_Number[a].GetComponent<SpriteRenderer>().enabled = true;*
    
  •  		yield return new WaitForSeconds (1f);*
    
  •  	}*
    
  •  	}*
    
  •  }*
    
  • }*
    This is the timer base. I tried making a static void which would start the coroutine and that void would be called from another scrip, but it doesn’t work.
    I’m using c#.

Create two scripts and attach them, for example, at Main Camera. The first script contains your timer with all variables:

 using UnityEngine;
 using System.Collections;

 public class myTimer : MonoBehaviour {
  //Create your variable
  ...
  //Your function timer
  public IEnumerator Counter() {
   ...
  }
 }

In the second script, for example, as Start () we will call the timer:

 using UnityEngine;
 using System.Collections;

 public class myCallTimer : MonoBehaviour {

  void Start() {
   //myTimer script attach at Main Camera, than
   StartCoroutine(Camera.main.GetComponent<myTimer>().Counter());
  }
 }

I hope that it will help you.

1 Like