GolfCup.cs
using Sandbox;

/// <summary>
/// The cup of a hole, on the kit's cup prefab: marks which object under the hole's group is the
/// cup, and owns the scoring trigger, a small box at the bottom of the cup whose size comes from
/// the group's <see cref="Hole"/> (Cup Radius and Cup Depth). The trigger is made here, kept in
/// step every frame and never saved, so nothing on the cup needs touching: change the Model
/// Renderer's model for a different cup and the trigger follows the hole's settings.
///
/// When a ball that is not holed reaches the trigger, the hole reports it
/// (<see cref="IGolfCourseEvents.OnBallInCup"/>) and the game finishes its owner.
/// </summary>
[Title( "Golf Cup" ), Icon( "sports_golf" )]
public sealed class GolfCup : Component, Component.ExecuteInEditor, Component.ITriggerListener
{
	/// <summary>The hole this cup belongs to: the nearest ancestor with a Golf Hole, or null.</summary>
	public Hole Hole => GameObject.GetComponentInParent<Hole>( true, true );

	BoxCollider _trigger;

	protected override void OnUpdate()
	{
		OwnTrigger();
	}

	protected override void OnEnabled()
	{
		OwnTrigger();
	}

	/// <summary>The trigger box where the hole wants it: hidden from the Inspector, never saved.</summary>
	void OwnTrigger()
	{
		var hole = Hole;
		var radius = hole.IsValid() ? hole.CupRadius : 4f;
		var depth = hole.IsValid() ? hole.CupDepth : 40f;

		if ( !_trigger.IsValid() )
		{
			// A cup saved by an older kit carries its trigger box already; take that one over.
			_trigger = GetComponent<BoxCollider>( true ) ?? Components.Create<BoxCollider>();
			_trigger.Flags |= ComponentFlags.NotSaved | ComponentFlags.Hidden | ComponentFlags.NotEditable;
		}

		var center = new Vector3( 0f, 0f, -depth );
		var size = new Vector3( radius * 2f, radius * 2f, 14f );
		if ( _trigger.Center != center ) _trigger.Center = center;
		if ( _trigger.Scale != size ) _trigger.Scale = size;
		if ( !_trigger.IsTrigger ) _trigger.IsTrigger = true;
		if ( !_trigger.Enabled ) _trigger.Enabled = true;
	}

	void Component.ITriggerListener.OnTriggerEnter( Collider other )
	{
		// Physics runs everywhere, but only the host decides what counts.
		if ( !Networking.IsHost ) return;
		if ( !other.IsValid() || !other.GameObject.IsValid() ) return;

		var ball = other.GameObject.GetComponentInParent<IGolfCourseBall>();
		if ( ball is null || ball.IsHoled ) return;

		var hole = Hole;
		if ( !hole.IsValid() ) return;
		IGolfCourseEvents.Post( x => x.OnBallInCup( hole, ball ) );
	}

	protected override void DrawGizmos()
	{
		var hole = Hole;
		var radius = hole.IsValid() ? hole.CupRadius : 4f;
		var depth = hole.IsValid() ? hole.CupDepth : 40f;
		Gizmo.Draw.Color = Color.Cyan.WithAlpha( Gizmo.IsSelected ? 0.9f : 0.35f );
		Gizmo.Draw.LineBBox( new BBox( new Vector3( -radius, -radius, -depth - 7f ), new Vector3( radius, radius, -depth + 7f ) ) );
	}
}