I am trying to make a cool looking explosion, but when I instantiate each phase of the explosion it all happens at once.
How would I delay each instantiation?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyByContact : MonoBehaviour {
public GameObject boom;
public GameObject boom2;
public GameObject boom3;
public GameObject playerBoom;
void OnTriggerEnter(Collider other) {
if (other.tag == "Boundary") {
return;
}
Instantiate (boom, transform.position, transform.rotation);
Instantiate(boom2, transform.position, transform.rotation);
Instantiate(boom3, transform.position, transform.rotation);
if (other.tag == "Player") {
Instantiate (playerBoom, other.transform.position, other.transform.rotation);
}
Destroy(other.gameObject);
Destroy(gameObject);
}
}
You could use a coroutine which would allow you to have delays between actions:
IEnumerator ExplosionsTask()
{
Instantiate (boom, transform.position, transform.rotation);
yield return new WaitForSeconds(1.0f)
Instantiate(boom2, transform.position, transform.rotation);
yield return new WaitForSeconds(1.0f)
Instantiate(boom3, transform.position, transform.rotation);
if (other.tag == "Player") {
yield return new WaitForSeconds(1.0f)
Instantiate (playerBoom, other.transform.position, other.transform.rotation);
}
Destroy(other.gameObject);
Destroy(gameObject);
}
And then start the coroutine like this in your OnTriggerEnter(…):
StartCoroutine(ExplosionTask());
Its worth noting that the coroutine is attached to the gameobject that creates it, so if you let the call to Destroy(gameObject); in OnTriggerEnter(…) it would stop the coroutine as well.