Component that manages an entity's health. Stores a sync'd health Value, updates a Vignette effect based on health, handles death by destroying the object and spawning ragdoll and spectator game objects, and exposes a broadcast RPC to apply damage.
using Sandbox;
public class Health : Component
{
[Property] public GameObject Ragdoll {get;set;}
[Sync, Property] public float Value {get;set;} = 100f;
[Property] public GameObject Spectator {get;set;}
Vignette vignette;
protected override void OnStart()
{vignette = Scene.Camera.GameObject.GetComponent<Vignette>();}
protected override void OnUpdate()
{
if (IsProxy) return;
if (Value <= 0) Die();
if (Input.Pressed("k")) Take(999);
if (Value <= 0) {vignette.Intensity = 0; return;}
vignette.Intensity = 1f - (Value / 100f);
}
void Die()
{ DestroyGameObject();
var ragdoll = Ragdoll.Clone(WorldPosition);
ragdoll.NetworkSpawn(Network.Owner);
var spectator = Spectator.Clone();
spectator.NetworkSpawn(Network.Owner);
}
[Rpc.Broadcast]
public void Take(float Amount)
{Value -= Amount;}
}