A component that implements a temporary shield ability for an entity. It tracks activation, duration, cooldown and toggles a visual GameObject while logging activation and expiry.
using Sandbox;
public sealed class ShieldAbility : Component
{
[Property] public float ShieldDuration { get; set; } = 5f;
[Property] public float Cooldown { get; set; } = 15f;
[Property] public GameObject ShieldVisual { get; set; }
public bool IsShieldActive { get; private set; } = false;
private TimeSince timeSinceActivated;
private TimeSince timeSinceCooldown;
private bool isCoolingDown = false;
protected override void OnStart()
{
if ( ShieldVisual.IsValid() )
{
ShieldVisual.Enabled = false;
}
}
protected override void OnUpdate()
{
if ( IsShieldActive && timeSinceActivated >= ShieldDuration )
{
DeactivateShield();
}
if ( Input.Pressed( "Flashlight" ) )
{
TryActivateShield();
}
}
public void TryActivateShield()
{
if ( IsShieldActive ) return;
if ( isCoolingDown && timeSinceCooldown < Cooldown ) return;
IsShieldActive = true;
timeSinceActivated = 0;
if ( ShieldVisual.IsValid() )
{
ShieldVisual.Enabled = true;
}
Log.Info( "[ShieldAbility] Shield Activated!" );
}
private void DeactivateShield()
{
IsShieldActive = false;
isCoolingDown = true;
timeSinceCooldown = 0;
if ( ShieldVisual.IsValid() )
{
ShieldVisual.Enabled = false;
}
Log.Info( "[ShieldAbility] Shield Expired!" );
}
}