A UI Razor component that renders a health bar. It finds a HealthComponent on a parent entity and renders a fill div whose width and hue are based on the current health percentage.
@using Sandbox;
@using Sandbox.UI;
@inherits PanelComponent
@namespace Sandbox
<root class="@(IsWorldPanel ? "full" : "")">
<div class="fill @(Health.IsRegening ? "" : "ease-transition")" style="width: @HealthPercent%; background: hsl(@Hue,85%,45%);"></div>
</root>
@code
{
private HealthComponent Health { get; set; }
private float HealthPercent => Health.MaxHealth <= 0 ? 0 : (Health.CurrentHealth / Health.MaxHealth) * 100f;
private float Hue => (@HealthPercent / 100) * 100;
[Property] bool IsWorldPanel { get; set; }
/// <summary>
/// the hash determines if the system should be rebuilt. If it changes, it will be rebuilt
/// </summary>
protected override int BuildHash() => System.HashCode.Combine(Health.CurrentHealth, Health.MaxHealth, IsWorldPanel);
protected override void OnStart()
{
Health = GetComponentInParent<HealthComponent>();
}
}