Created
June 3, 2021 21:23
-
-
Save kurtdekker/cae3c999eee5c3ab419b952dd13e0971 to your computer and use it in GitHub Desktop.
TTL - TimeToLive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.