# Make enemy disappear after spawn

I have enemies that spawn in different positions but what I want to do is that if you don't kill it after three seconds, the enemy disappears (but the spawning keeps happening of course, the enemy will show up again eventually). I tried using a coroutine but after reading the documentation and watching some tutorials I still don't understand very well how it works so I need some help. Thanks in advance. This is my code so far:

public class TimedSpawn : MonoBehaviour {

public GameObject spawnee;
public bool stopSpawning;
public float spawnTime;
public float spawnDelay;

private GameManagerScript GMS;

void Start ()
{
GMS = GameObject.Find ("GameManager").GetComponent<GameManagerScript> ();
InvokeRepeating ("SpawnObject", spawnTime, spawnDelay);
}

public void SpawnObject ()
{
if  (GMS.counterDownDone == true){

Instantiate (spawnee, transform.position, transform.rotation);
}

if (stopSpawning) {
CancelInvoke ("SpawnObject");
}
}
}

• What's the question? How to trigger code after a given time? – Jacob Persi Nov 30 '17 at 20:45

You can call Destroy with a 2nd parameter indicating the delay before the destroy occurs :

public void SpawnObject ()
{
if  (GMS.counterDownDone == true)
{
Destroy( Instantiate (spawnee, transform.position, transform.rotation), 3 );
}

if (stopSpawning) {
CancelInvoke ("SpawnObject");
}
}