Coroutine doesn't work

I've been trying to make this work for days and I can't figure it out. I have a code, attached to an enemy prefab, that should display an image a couple seconds after an enemy spawns (this is to show the player it has been attacked). I don't get an error in the console, but it doesn't work either. This is the code:

public class enemyAttack : MonoBehaviour {

public float time = 5;
private IEnumerator coroutine;
public Image image;
private float t = 5f;

void Start ()
{
image.enabled = false;
StartCoroutine(playerIsAttacked (time, image));

}

IEnumerator playerIsAttacked (float t, Image im)
{
im.enabled = true;
yield return new WaitForSeconds (t);

StartCoroutine (playerIsAttacked (t, im));
}


}

Thank you in advance for the help.

• I'm pretty sure there's something wrong if you're calling StartCoroutine found the coroutine. – Almo Nov 14 '17 at 20:24

What exactly "Doesn't work"? I assume what you mean is "the image starts off as visible from the beginning, but I want it to be invisible and appear 5 seconds later.". This is because you've enabled the image first (im.enabled = true), and then wait for 5 seconds (yield return new WaitForSeconds (t);):

im.enabled = true;
yield return new WaitForSeconds (t);


You probably meant to wait for 5 seconds first, and then set im.enabled = true afterwards.

Also, unless you want to run the code again every 5 seconds after that, you shouldn't call StartCoroutine again inside playerIsAttacked.

• When i say it doesn't work i mean that the image never displays in the first place. But yes i want it to wait 5 seconds before being visible. I changed what you said but it still doesn't work. – detdimples Nov 14 '17 at 21:00
• Works on my machine: youtube.com/watch?v=Ux6nO2rlP1E&feature=youtu.be -- maybe your Image field is linked to the wrong image? Maybe the image is not in the camera's view? Maybe the image is transparent? There's not enough information in the question to figure out what exactly could be your issue. – Jimmy Nov 14 '17 at 21:13
• Thank you so much for that video because now it works, but it doesn't happen five seconds after an enemy spawns, just five seconds after i start the level – detdimples Nov 14 '17 at 21:52
• Because the code in the video calls StartCoroutine in Start(). You'll need to call StartRoutine in your enemy spawning function, if you want it to happen 5 seconds after that. – Jimmy Nov 14 '17 at 21:55