- Home /
How to start a Coroutine in another script?
Hello! I did some research about this but what i found was kinda confusing so I didn't actually understand it. Basically I have a coroutine that displays an image after 5 seconds, but I want that image to display 5 seconds after an enemy spawns. I understand that what I need to do is call StartCoroutine in my enemy spawning function, but I'm very new to programming and i couldn't do it, even though it's probably something really easy.
Here's the code that displays the image:
public class enemyAttack : MonoBehaviour {
public Image TargetImage;
void Start ()
{
TargetImage.enabled = false;
StartCoroutine(playerIsAttacked (5, TargetImage));
}
public IEnumerator playerIsAttacked (float t, Image im)
{
yield return new WaitForSeconds (t);
TargetImage.enabled = true;
}
}
and this is the code that spawns the enemies:
public class TimedSpawn : MonoBehaviour {
public GameObject spawnee;
public bool stopSpawning;
public float spawnTime;
public float spawnDelay;
void Start () {
InvokeRepeating ("SpawnObject", spawnTime, spawnDelay);
}
public void SpawnObject (){
Instantiate (spawnee, transform.position, transform.rotation);
if (stopSpawning) {
CancelInvoke ("SpawnObject");
}
}
}
@delfinatarga Hmm, i'm kind lost here, enemyAttack is your spawned enemy? if so your code should work just fine, when it's istantiated Start method will be called and after 5s the TargetImage will be enabled.
Answer by shadowpuppet · Nov 14, 2017 at 11:42 PM
A number of ways to do this...some better than others. I'm a bit of a novice as well so don't get parts of your script so I'll start from scratch. I'd have this script on the image disabled, then when the enemy spawns, enable it the script , and have your coroutine start in the OnEnable function rather than the start function. maybe start a second coroutine as well to turn off image then disable script again for next spawn. So in this script when enabled will wait 5 seconds, then show text, and 5 seconds later turn it off and disable the script again
public class enemyAttack : MonoBehaviour {
public Image TargetImage;
public int TextTimer= 5;
void OnEnable ()
{
StartCoroutine(DelayBeforeText ());
}
private IEnumerator DelayBeforeText(){
yield return new WaitForSeconds(TextTimer);
TargetImage.enabled = true;
StartCoroutine(DelayBeforeTextEnds ());
}
private IEnumerator DelayBeforeTextEnds(){
yield return new WaitForSeconds(TextTimer);
TargetImage.enabled = false;
this.enabled = false;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612142850im_/https://answers.unity.com/themes/thub/images/avi.jpg)