0
\$\begingroup\$

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");
        }
    }
 }
\$\endgroup\$
1
  • \$\begingroup\$ What's the question? How to trigger code after a given time? \$\endgroup\$
    – user99319
    Commented Nov 30, 2017 at 20:45

1 Answer 1

1
\$\begingroup\$

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");
    }
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .