Script to Despawn Destroyed Crate Pieces

I wanted the crate pieces to destroy themselves after an amount of time elapsed. I created a super basic new cs script and attached it to the crate destroyed prefab. This script could also be added to ragdoll prefabs if you want dead units to despawn too.

using UnityEngine;

public class Despawner : MonoBehaviour
{
private float timer;

private void Start()
{
    timer = 4f;
}
private void Update()
{
    CountdownToDespawn();

    if (timer <= 0f)
    {
        Destroy(gameObject);
    }
}
private void CountdownToDespawn()
{
    timer -= Time.deltaTime;
}

}

Very good, but you know Destroy has this built in, right? You can just use Destroy(gameObject, 4f) and the game object will be destroyed after 4 seconds.

Destroy Documentation

1 Like

Privacy & Terms