UnityGameProjectsCode / RelianceGame / Helper Scripts / DestroyAfterTime.cs
DestroyAfterTime.cs
Raw
using System.Collections.Generic;
using UnityEngine;

public class DestroyAfterTime : MonoBehaviour
{
    public float timeToDestroy;

    public bool multiStageDeletion;
    public List<GameObject> objectsToDelete = new List<GameObject>();
    public List<float> timeStamps = new List<float>();

    private float timeSinceCreation;

    private void Awake()
    {
        if (multiStageDeletion)
        {
            for (int i = 0; i < timeStamps.Count; i++)
            {
                if (timeStamps[i] > timeToDestroy)
                {
                    Debug.LogError("The time stamp at position " + i + " is set beyond the objects lifetime and will not work properly. Please set the time stamp to a value below the time to destroy.");
                }

                if (objectsToDelete[i] == null)
                {
                    Debug.LogError("The time stamp at position " + i + " is set but has no game object associated with it for deletion. Please place a game object to the same index for the objects to delete list.");
                }

                if (timeStamps[i] == 0)
                {
                    Debug.LogError("The time stamp at position " + i + " is set to 0. Please raise this value above 0 to allow proper use of the time stamps.");
                }
            }

            for (int i = 0; i < objectsToDelete.Count; i++)
            {
                if (objectsToDelete[i] != null && timeStamps[i] == 0)
                {
                    Debug.LogError("The game object at position " + i + " has no valid time stamp associated with it. Please set a time stamp for all game objects in the list.");
                }
            }
        }
    }
    private void Update()
    {
        timeSinceCreation += Time.deltaTime;

        if (!multiStageDeletion)
        {
            if (timeSinceCreation >= timeToDestroy)
                Destroy(this.gameObject);
        }
        else
        {
            if (objectsToDelete.Count == 0)
            {
                if (timeSinceCreation >= timeToDestroy)
                    Destroy(this.gameObject);
            }
            else
            {
                for (int i = 0; i < timeStamps.Count; i++)
                {
                    if (timeSinceCreation >= timeStamps[i])
                    {
                        GameObject temp = objectsToDelete[i];
                        objectsToDelete.RemoveAt(i);
                        Destroy(temp);
                    }
                }
            }
        }
    }
}