Skip to content

Instantly share code, notes, and snippets.

@kurtdekker
Created June 3, 2021 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kurtdekker/cae3c999eee5c3ab419b952dd13e0971 to your computer and use it in GitHub Desktop.
Save kurtdekker/cae3c999eee5c3ab419b952dd13e0971 to your computer and use it in GitHub Desktop.
TTL - TimeToLive
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TTL : MonoBehaviour
{
public float AgeLimit;
float age;
public System.Action<GameObject> Callback;
void Reset()
{
AgeLimit = 2.0f;
}
public static TTL Attach( GameObject go, float agelimit)
{
TTL ttl = go.AddComponent<TTL>();
ttl.AgeLimit = agelimit;
return ttl;
}
void Update ()
{
if (age > AgeLimit)
{
if (Callback != null)
{
Callback(gameObject);
}
Destroy(gameObject);
return;
}
age += Time.deltaTime;
}
}
@kurtdekker
Copy link
Author

To use, any ONE of these methods is valid:

  • drag/drop it on a GameObject / Prefab, set the ageLimit field as desired

  • call TTL.Attach(myDoomedGameObject, 2.0f); to doom your GameObject

  • just use AddComponent() yourself if you prefer

Optionally you can supply a Callback function that will be called at the time of destruction.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment