/// <summary>
/// Provides a game object that automatically self terminates.
/// </summary>
[ExecuteInEditMode]
public class SelfTerminatingObject : MonoBehaviour
{
/// <summary>
/// Holds a reference to a callback that will be called just before termination.
/// </summary>
public Action Callback;
/// <summary>
/// Holds the time delay in seconds before object self terminates.
/// </summary>
public float Delay;
/// <summary>
/// Holds a time value used to determine whether it's time to self terminate.
/// </summary>
private DateTime lastTime;
/// <summary>
/// Called by Unity to update the object.
/// </summary>
public void Update()
{
this.PerformCheck();
}
/// <summary>
/// Called by Unity to draw the object's GUI.
/// </summary>
public void OnGui()
{
this.PerformCheck();
}
/// <summary>
/// Determines whether it's time to terminate.
/// </summary>
private void PerformCheck()
{
// check if specified time span has elapsed
if (DateTime.Now > this.lastTime + TimeSpan.FromSeconds(this.Delay))
{
// run callback is specified
if (this.Callback != null)
{
this.Callback();
}
// destroy object
#if UNITY_EDITOR
DestroyImmediate(this.gameObject, true);
#else
Destroy(this.gameObject);
#endif
}
}
/// <summary>
/// Creates a self terminating game object.
/// </summary>
/// <param name="callback">The method to be called before the object terminates.</param>
/// <returns>Returns a reference to the game object that will self terminate.</returns>
public static GameObject CreateUpdateCallback(Action callback)
{
return CreateUpdateCallback(callback, 0);
}
/// <summary>
/// Creates a self terminating game object.
/// </summary>
/// <param name="callback">The method to be called before the object terminates.</param>
/// <param name="delay">Specifies a delay value in seconds before the object will self terminate.</param>
/// <returns>Returns a reference to the game object that will self terminate.</returns>
public static GameObject CreateUpdateCallback(Action callback, float delay)
{
var obj = new GameObject();
var com = obj.AddComponent<SelfTerminatingObject>();
com.lastTime = DateTime.Now;
com.Delay = delay;
com.Callback = callback;
return obj;
}
}