Code/RespawnAlMorir.cs

Component for player objects that listens for death and respawns the entity at a random SpawnPoint, plays an optional death sound, then fully revives the Vida component.

NetworkingFile Access
namespace SBH;

using Sandbox;
using System.Linq;

/// <summary>
/// Al morir la Vida de este GameObject, lo teletransporta a un
/// SpawnPoint aleatorio y lo revive. Para jugadores.
/// </summary>
public sealed class RespawnAlMorir : Component
{
	[RequireComponent] Vida Vida { get; set; }

	[Property, Description( "Sonido al morir (opcional)" )]
	public SoundEvent SonidoMuerte { get; set; }

	protected override void OnEnabled()
	{
		Vida.AlMorir += Respawnear;
	}

	protected override void OnDisabled()
	{
		Vida.AlMorir -= Respawnear;
	}

	void Respawnear()
	{
		if ( SonidoMuerte != null )
			Sound.Play( SonidoMuerte, WorldPosition );

		var spawns = Scene.GetAllComponents<SpawnPoint>().ToList();
		if ( spawns.Count > 0 )
		{
			var spawn = Game.Random.FromList( spawns );
			WorldPosition = spawn.WorldPosition;
		}

		Vida.Revivir();
		Log.Info( "💀 Jugador muerto → respawn con vida completa" );
	}
}