Skip to content

Instantly share code, notes, and snippets.

@RyanNielson
Last active August 29, 2015 14:22
Show Gist options
  • Save RyanNielson/9bd50a6a399b8133dfa8 to your computer and use it in GitHub Desktop.
Save RyanNielson/9bd50a6a399b8133dfa8 to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
public class LifeSpan : MonoBehaviour
{
[SerializeField, Tooltip("How long this GameObject lives before dying, 0 = forever.")]
private float initialLifeSpan = 0;
private IEnumerator lifeSpanExpiredCoroutine = null;
private void Start()
{
SetLifeSpan(initialLifeSpan);
}
/// <summary>
/// Set the life span of this GameObject. When it expires, the GameObject will be destroyed.
/// </summary>
/// <param name="lifeSpan">The life span, in seconds, before this GameObject is destroyed. If 0, the timer is cleared and the GameObject will not be destroyed</param>
public void SetLifeSpan(float lifeSpan)
{
if (lifeSpanExpiredCoroutine != null)
{
StopCoroutine(lifeSpanExpiredCoroutine);
}
if (lifeSpan > 0f)
{
lifeSpanExpiredCoroutine = LifeSpanExpired(lifeSpan);
StartCoroutine(lifeSpanExpiredCoroutine);
}
}
private IEnumerator LifeSpanExpired(float lifeSpan)
{
yield return new WaitForSeconds(lifeSpan);
Destroy(gameObject);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment