swb_shared/extensions/GameObjectExtensions.cs

A small component and extension for GameObjects that destroys the GameObject after a timed delay. TimedDestroyComponent stores a Time and a TimeUntilDestroy countdown, sets the countdown on start, and destroys the GameObject when the countdown expires. GameObjectExtensions adds DestroyAsync to attach the component with a specified delay.

Native Interop
🐞 The OnFixedUpdate check uses 'if ( TimeUntilDestroy )' which relies on implicit conversion; if TimeUntil type does not have an implicit bool operator this will not compile or behave incorrectly.
namespace SWB.Shared;

public sealed class TimedDestroyComponent : Component
{
	/// <summary>
	/// How long until we destroy the GameObject.
	/// </summary>
	[Property] public float Time { get; set; } = 1f;

	/// <summary>
	/// The real time until we destroy the GameObject.
	/// </summary>
	[Property, ReadOnly] TimeUntil TimeUntilDestroy { get; set; } = 0;

	protected override void OnStart()
	{
		TimeUntilDestroy = Time;
	}

	protected override void OnFixedUpdate()
	{
		if ( TimeUntilDestroy )
			GameObject.Destroy();
	}
}

public static class GameObjectExtensions
{
	public static void DestroyAsync( this GameObject self, float seconds = 1.0f )
	{
		var component = self.Components.Create<TimedDestroyComponent>();
		component.Time = seconds;
	}
}