Flashlight.cs

Component that controls a player's flashlight. It holds a SpotLight and a SoundPointComponent, tracks on/off state network-synced, toggles the light, and optionally plays a sound when toggled.

Networking
using Sandbox;

public sealed class Flashlight : Component
{
	[Property] public SpotLight Light { get; private set; }
	[Property] public SoundPointComponent Sound { get; private set; }

	[Sync, Change( nameof(OnLightStateChange) )] public bool IsOn { get; private set; }

	protected override void OnStart()
	{
		OnLightToggle( false );
	}

	public void Toggle()
	{
		IsOn = !IsOn;
	}

	private void OnLightStateChange( bool oldVal, bool newVal ) => OnLightToggle();

	public void OnLightToggle(bool playSound = true)
	{
		Light.Enabled = IsOn;

		if ( playSound )
			Sound.StartSound();
	}
}