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\$
  • \$\begingroup\$ What's the question? How to trigger code after a given time? \$\endgroup\$ – Jacob Persi Nov 30 '17 at 20:45
2
\$\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\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.