C#

How to auto destroy a game object after a few seconds in Unity

ยท 1 min read
How to auto destroy a game object after a few seconds in Unity
destroy a game object

Image we have a gameobject with a script SelfExplode attached to it. We want this specific gameobject explode with 60 seconds after spawn.

Full script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SelfExplode : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(WaitAndDestory(60.0f));
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    private IEnumerator WaitAndDestory(float waitTime)
    {
        yield return new WaitForSeconds(waitTime);
        Debug.Log("Waited for " + waitTime + " seconds");
        Destroy(gameObject);
    }
}

This can be used in scenarios such as a bullet/missile shot out and self destroyed in a certain time.