scripts/spawnpoint.cs

Component that moves a player GameObject to a random SpawnPoint found under a specified map GameObject or the Scene. It finds spawn points by walking the object tree, picks one at random, sets player WorldPosition plus offset, and aligns player yaw to the spawn rotation.

Networking
using Sandbox;
using System;


public sealed class GotoSpawnPoint : Component
{
	[Property]
	public GameObject? map;
	[Property]
	public GameObject? player;
	[Property]
	public Vector3 offset = new();

	protected override void OnStart()
	{
		player ??= Scene.GetComponentInChildren<PlayerController>().GameObject.Parent;
		map ??= Scene.GetComponentInChildren<MapInstance>().GameObject;

		var spawns = FindPlayerSpawns( map );
		Log.Info( spawns.Count);
		var spawn = new Random().FromList( spawns );
		if ( spawn == null ) { Log.Warning( "Failed to find spawn points" ); return; }

		player.WorldPosition = spawn.WorldPosition + offset;

		var yang = spawn.WorldRotation.Angles();
		var	ang = spawn.WorldRotation.Angles();

		ang.yaw = yang.yaw;
		player.WorldRotation = ang;
	}


	List<GameObject> FindPlayerSpawns( GameObject? gameobj )
	{
		List<GameObject> spawns = new();
		HashSet<GameObject> blacklist = new();

		void Helper( GameObject obj )
		{
			foreach ( var child in obj.Children )
			{
				if ( !blacklist.Add( child ) )
					continue;

				if ( child.GetComponent<SpawnPoint>() != null )
					spawns.Add( child );

				Helper( child );
			}
		}

		Helper( gameobj ?? Scene );

		return spawns;
	}

}