Last active
August 29, 2015 14:22
-
-
Save RyanNielson/9bd50a6a399b8133dfa8 to your computer and use it in GitHub Desktop.
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 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