How to destroy in an amount of time

using UnityEngine;

public class Despawner : MonoBehaviour {

public float waitTime = 2.0f;
float timer;

void Update()
{
    timer += Time.deltaTime;
}

void OnCollisionEnter(Collision col)
{
    if (col.gameObject.name == "Despawner")
    {
        if (timer > waitTime)
        {
            Destroy(gameObject);
            timer = 0f;
        }
    }
}

I am trying to destroy an object after 1 second when a collision happens with another object but it instantly gets destroyed, not after the wait time.

1 Answer

1

// Kills the game object in 5 seconds after loading the object Destroy(gameObject, 5);

This line is ripped from the documentation about Destroy

Destroy(gameObject, 5);

Thank You!!!