Skip to main content

Player

A class in Root.Township, the global namespace.

The network entity for a connected player. It is not the body: it holds the account, save, states, progression and inputs, and links to the current PlayerController. Both sides; find one with Player.AllPlayers, Player.Get(userId) or Player.Current on a client.

Constructors​

MemberWhat it is
Player()Unity makes components itself; use AddComponent or spawn a prefab instead of new.

Fields​

26 private and internal fields
MemberWhat it is
private readonly List<NetworkEntity> associatedObjectsEntities spawned for this player (such as the controller) that are destroyed with it in DestroyPlayerControllerAndOldEntities.
private static Player currentBacking field for Current, the local player.
private PlayerEventsManager eventsManagerBacking field for PlayerEventsManager.
private bool isStartedSet by StartUp so the server only loads the player's save or default state once.
private PlayerInput leftPlayerInputBacking field for LeftInput.
private TaskCompletionSource<bool> loadStatusTaskServer: completed when the client answers the chunk load handshake in SyncLoadStatus.
private static readonly Logger loggerNLog logger for this class.
private static readonly Dictionary<int, IPlayer> lookupPlayers by user ID, read by the static Get.
private PlatformTarget platformTargetBacking field for PlatformTarget.
private PlayerComponent[] playerComponentsPlayerComponents on this object, each initialised with the player in Awake.
private PlayerController playerControllerBacking field for PlayerController.
private PlayerMode playerModeBacking field for PlayerMode.
private PlayerProgressionManager progressionManagerBacking field for ProgressionManager.
private IPlayerRespawnPositionProvider respawnPositionProviderInjected provider that picks the respawn position.
private PlayerInput rightPlayerInputBacking field for RightInput.
private readonly HashSet<object> saveBlockersObjects currently blocking saves; while it isn't empty, IsSavingBlocked is true.
private PlayerSave saveDataThe player's loaded PlayerSave, exposed through Save.
private IAltaFile saveFileServer: the player's save file. With no save file the player is never in a savable state.
private MethodSync setLocalMessage sync that tells a client this player entity is its local player.
private PlayerStateManager stateManagerBacking field for StateManager.
private MethodSync syncCosmeticsMessage sync for SyncCosmetics.
private MethodSyncStruct<Vector3> syncLastSafePositionMessage sync for SyncLastSafePosition.
private MethodSyncStruct<uint> syncLoadStatusMessage sync for SyncLoadStatus.
private MethodSync syncModeControllerAndUserInfoWithRemoteMessage sync for SyncModeControllerAndUserInfoWithRemote.
private PlayerUnlockManager unlockManagerBacking field for UnlockManager.
private PlayerMode validSavingModesSerialized player mode flags. Not read anywhere in the code.

Properties​

MemberWhat it is
static HashSet<IPlayer> AllPlayers { get; }Every player entity in the scene, on both sides.
PlayerChunkManager ChunkManager { get; private set; }The player's PlayerChunkManager, which loads chunks around them. Created on the server at initialize.
Connection ConnectionToRemotePlayer { get; private set; }Server: the network connection to this player. Null on clients.
static IPlayer Current { get; }Client: the local player. Null on a dedicated server.
PlayerCharacterCustomizationManager Customization { get; }The player's cosmetics, loaded from their save.
DamageDisplayer DamageDisplayer { get; private set; }Tracks damage this player has dealt, for debug displays.
FriendshipManager FriendshipManager { get; }Tracks this player's friends.
bool IsLoaded { get; set; }Client: false while the local player waits for its chunk to finish loading (screen faded out), set by PlayerController.WaitForChunkLoad.
bool IsLocalPlayer { get; }True on a client for the player it controls.
bool IsSavingBlocked { get; }True while any save blocker is held.
PlayerInput LeftInput { get; }The left hand's PlayerInput.
HashSet<Chunk> LoadedChunks { get; }Server: the chunks currently loaded for this player, kept by each chunk's player manager.
PlatformTarget PlatformTarget { get; set; }The platform the player is on. Setting it raises PlayerSystemChanged.
PlayerCharacter PlayerCharacter { get; }The current body as a PlayerCharacter. A hard cast.
PlayerController PlayerController { get; private set; }The body the player controls, or null between spawns. Setting it raises PlayerControllerSet.
PlayerEventsManager PlayerEventsManager { get; }The player's event hub component.
PlayerMode PlayerMode { get; set; }How the player joined (VR, fly, autocam and so on).
Transform PlayerTransform { get; }The body's transform, or the player entity's own if there's no body.
Vector3? Position { get; set; }Cached head position, refreshed by AgentUpdater for AI use, or null when the player has no controller.
PlayerProgressionManager ProgressionManager { get; }The player's skills and progression.
PlayerInput RightInput { get; }The right hand's PlayerInput.
PlayerSave Save { get; }Server: the player's PlayerSave in memory, created at join if they had none. Null on clients.
PlayerStateManager StateManager { get; }The player's state stack.
string UnityObjectName { get; }The GameObject's name.
PlayerUnlockManager UnlockManager { get; }Which unlocks the player has.
UserInfoAndRole UserInfo { get; private set; }The player's account id, username and member status.
IParticipant Voice { get; set; }The player's Vivox voice participant.

Events​

MemberWhat it is
event Action<PlayerController> FinishedLoadingControllerRaised on the server after a new body is spawned and linked.
event Action LoadCompleteRaised after LoadFrom has restored the entity, states and progression.
static event PlayerHandler LocalPlayerSetStatic. Raised on a client when the local player is known.
static event Action<Player> OnPlayerAddedStatic. Raised when a player entity is initialized.
static event Action<Player> OnPlayerRemovedStatic. Raised when a player entity is destroyed.
event PlatformHandler PlatformChangedRaised when PlayerMode changes, with the new mode.
event PlayerControllerHandler PlayerControllerSetRaised when the body is linked or unlinked. Exceptions in handlers are caught and logged.
event PlayerSystemHandler PlayerSystemChangedRaised when PlatformTarget changes. PlayerChunkManager listens to pick its loader.

Methods​

MemberWhat it is
void AddSaveBlocker(object blocker)Stops this player being saved until the same object is passed to RemoveSaveBlocker.
void AddToAssociatedObjects(NetworkEntity entity)Server: records an entity (like the body) to be destroyed with the player.
void DestroyPlayerControllerAndOldEntities(bool isUndocking, bool isUnloading)Server: unlinks the body and destroys every associated entity, optionally undocking what's in them first.
void DestroyWithAssociatedObjects()Server: destroys the body and associated entities, then the player entity.
static IPlayer Get(int userId)Looks up a player by user id from a dictionary. Faster than GetPlayer.
static Player GetPlayer(int playerId)Finds a player by user id, or by username ignoring case. Null if not here.
static Player GetPlayer(string playerName)Finds a player by user id, or by username ignoring case. Null if not here.
Vector3 GetSpawnPosition(bool isRespawning)Their saved position on join, or the respawn point (home if set) when respawning. Fly mode uses the scene spawn point.
override void Initialize(INetworkScene scene, NetworkEntity parent, uint identifier, uint[] embeddedIdentifiers, bool isInitializingBehaviours)Sets up the player's sync messages and adds it to AllPlayers.
async Task InitializePlayerOnServer(Connection connection, PlayerMode playerMode, PlatformTarget platformTarget, IAltaFile saveFile)Server: binds the player to its connection, user info, mode and save file, and loads cosmetics.
bool IsInSavableState(bool isSavingIfDead = false)False with saving off, in fly or autocam mode, in the character room, dead (unless allowed), or with a save blocker.
static bool IsOnServer(int playerId)Whether a player with that user id is connected.
void Kick(string reason)Server: disconnects the player and logs the reason.
void LinkPlayerControllerToPlayer(PlayerController playerController, bool isSettingControllerOwner = true)Makes a body this player's PlayerController and hooks up the hand inputs.
void LoadFrom(PlayerSave save)Server: restores the player entity, state stack and progression from a PlayerSave.
override void OnConnected(Player player)Server: sends this player's mode, user info, cosmetics, states and practiced skills to the joining player.
void RemoveSaveBlocker(object blocker)Removes a blocker added with AddSaveBlocker.
static bool SafeGetPlayer(int playerId, out Player result)Finds a player by user id and returns whether it was found.
async void SafeMoveToChunk(LocationChunk chunk, Vector3 controllerPosition, Action callback)Server: parks the body in the void chunk until the client has loaded the target chunk, then moves it there and calls back.
static void SaveAll()Server: saves every player and writes their files. Errors per player are logged and skipped.
void SaveControllerAndState(bool isSavingIfDead = false)Server: copies body, states and progression into Save. A dead body's position is set to home.
void SendLastSafePositionToClient(Vector3 newLastSafePosition)Server: tells the player's client its last safe position.
void SendLastSafePositionToServer(Vector3 newLastSafePosition)Client: reports a new last safe position, which the server stores in the save.
void SetLocal()Server: tells this player's client that this entity is them.
async Task SpawnNewController(PlayerController controllerPrefab, bool isRespawn)Server: spawns a new body at the join or respawn position, after the client has loaded that chunk.
async Task SpawnNewControllerAtPointInChunk(PlayerController controllerPrefab, SpawnPoint spawnPoint, LocationChunk chunk, bool isLoadingSave = true)Server: spawns a new body at a spawn point in a chunk, optionally without loading the saved body.
void StartUp()Server: loads the player's save, or starts the default state if there is none. Runs once.
void SyncCosmeticsToOthers()Sends this player's cosmetics to everyone who has them loaded.
override string ToString()[Player <user info>].
void UnlinkPlayerController()Detaches the current body from the player and clears the hand targets.
void WriteSave(bool isUnloading)Server: serializes the player entity into Save and starts writing the file. Runs even for dead players.
protected override void Awake()Wires up the state manager, hand inputs and PlayerComponents.
protected void Inject(IPlayerRespawnPositionProvider respawnPositionProvider)Dependency injection hook that supplies the respawn position provider.
30 private and internal methods
MemberWhat it is
private async Task AwaitRemoteClientToLoadChunk(LocationChunk chunk, Vector3 positionInChunk)Server: loads the chunk for this player, then waits until the client reports it has fully loaded it (skipped for the local player).
private void DelayUpdateFriendShip()Updates this remote player's friend status once the local player's friend list has finished loading.
private LocationChunk GetDefaultSpawnChunkAndUpdatePosition(ref Vector3 spawnPosition)Server: picks a random respawn position when the spawn chunk is null and returns the location chunk that contains it.
private PlayerSave GetPlayerSave()Getter behind Save: returns the loaded PlayerSave, creating an empty one if there is a save file but no data.
private Transform GetPlayerTransform()Getter behind PlayerTransform: the controller's transform if there is a live controller, else the Player object's own transform.
private Vector3 GetRespawnPoint()Server: respawn position from the respawn provider, replaced by the saved home position when the provider only has the default.
private Vector3 GetServerJoinSpawnPoint()Server: where the player appears on joining: their saved position, or the scene spawn point if none is saved.
private void HandleInteractor(Interactor interactor)Force-stops an interactor's interaction if it holds something whose base save mode isn't Base. Probably unused.
private void HandleStateActivation(IPlayerState playerState)Local player: when a player state activates, removes and adds the controller modes listed in its settings on both hands.
private void HandleStateDeactivation(IPlayerState playerState)Local player: undoes HandleStateActivation when a player state ends, restoring the controller modes.
private void InvokePlayerControllerSetListeners()Raises PlayerControllerSet, calling each listener separately and logging any exception instead of stopping.
private void ListenForStateChanges(IPlayer localPlayer)Hooked to LocalPlayerSet in Awake: once this player becomes the local player, subscribes to its state changes.
private async Task LoadCosmetics()Server: loads the player's cosmetics from the save data, if their player mode uses cosmetics.
private void LoadPlayerControllerFromSave(Vector3 spawnPosition)Server: moves the new controller to the spawn position and loads its saved state, if the server has saves and the mode allows it.
private void OnDestroy()Removes the player from the lookup and AllPlayers, clears the local-player chunk if it was local, and raises OnPlayerRemoved.
private void IPlatformPlayer.OnDisconnectedFromPlatform()Only logs that the player disconnected from the platform.
private void ReplyFullyLoaded(Chunk chunk)Client: tells the server the chunk it was asked to load has now fully loaded.
private void ReplyNoQueuedMessages()Client: tells the server it has finished loading once all queued connection messages are done. Not hooked up in this class.
private void SetCurrent(IPlayer player)Sets this as the local player (Current) and raises LocalPlayerSet.
private void SetLocal(IPlayer player, Stream stream)Server: tells this player's client that this entity is them.
private void SetPlatformTarget(PlatformTarget target)Setter behind PlatformTarget: raises PlayerSystemChanged and stores the new target when it changes.
private void SetPlayerController(PlayerController controller)Setter behind PlayerController: stores the controller and raises PlayerControllerSet.
private void SetPlayerMode(PlayerMode mode)Setter behind PlayerMode: raises PlatformChanged and stores the new mode when it changes.
private void SpawnController(PlayerController controllerPrefab, Chunk chunk, Vector3 spawnPosition, bool isLoadingSave = true)Server: spawns the controller prefab at a position, links it to this player, loads its save if asked, and puts it in the chunk.
private async Task SpawnNewControllerAtPointInChunk(PlayerController controllerPrefab, LocationChunk chunk, Vector3 spawnPosition, bool isLoadingSave = true)Server: spawns a new body at a spawn point in a chunk, optionally without loading the saved body.
private IEnumerator StartPlayerModePlatform() (iterator)Client: coroutine that stops the active XR platform if it doesn't match the player mode and sets up the right one.
private async void SyncCosmetics(IPlayer player, Stream stream)Synced message that sends the player's cosmetics. The server rejects and logs cosmetics sent by anyone but this player.
private void SyncLastSafePosition(IPlayer player, Stream stream, Vector3 lastSafePosition)Synced message for the last safe position: updates smooth locomotion on the local player and the save on the server.
private void SyncLoadStatus(IPlayer player, Stream stream, uint chunkIndex)Synced chunk load handshake: the server sends a chunk index, the client replies once that chunk has fully loaded.
private void SyncModeControllerAndUserInfoWithRemote(IPlayer player, Stream stream)Synced message with the player mode, user ID, name and member status. Clients use it to fill UserInfo and friend status.

Used in​

Members of other types that take, return or hold a Player:

ActionItem.OnConnected, AdditionalStaticContent.OnConnected, AfkTimer.PlayerControllerSet, AfkTimer.PlayerJoined, AfkTimer.PlayerLeft, AfkTimer.ResetTimeout, AfkTimer.StopTimeout, AfkTimer.timeouts, AfkTimer.WaitForTimeout, ForgedModel<TB, TA>.OnConnected, Recycler.OnConnected, Smelter.OnConnected, Smelter.smeltingPlayers, ChisellingDeck.OnConnected, TimberBlock.OnConnected, TimberBlock.ReleaseResult, TimberBlockSpawner.OnConnected, TimberPieceBase.LastHittingPlayerController, CaveLayerManager.OnConnected, CaveTeleporter.OnConnected, CaveTeleporterManager.OnConnected, GenerationBase.OnConnected, PlayerCharacter.OnConnected, CaveLayerChunk.PlayerEnteredChunk, CaveLayerStreamer.OnConnected, Chunk.OnConnected, ChunkEntityManager.CompareFeet, ChunkPlayerManager.Add, ChunkPlayerManager.ItemAdded, ChunkPlayerManager.ItemRemoved, ChunkPlayerManager.Items, ChunkPlayerManager.OnItemAdded, ChunkPlayerManager.OnItemRemoved, ChunkPlayerManager.players, ChunkPlayerManager.Remove, ChunkSync.InitializeAndStart, ChunkSync.player, ChunkSync.Player, ChunkSync.Start, LocationChunk.PlayerEnteredChunk, PlayerEntitySyncServer.gradualSync, PlayerEntitySyncServer.LoadForPlayer, PlayerEntitySyncServer.StartSync, PlayerEntitySyncServer.StopSync, PlayerEntitySyncServer.UnloadForPlayer, StaticCaveChunk.OnConnected, DebuggingCommandModule.SpawnLoadMarker, DebuggingCommandModule.SpawnQASet, RepairBoxModule.SpawnBox, SelectionCommandModule.FindObjects, SelectionCommandModule.FindPrefab, SelectionCommandModule.LookAt, SpawnCommandModule.SpawnPopulation, WackyCommandModule.UnveilMap, CookingGarnishComponent.Alta.Cooking.ICookingGarnishMarker.CookingPlayer, ICookingGarnishMarker.CookingPlayer, StewManager.cookingPlayers, StewManager.OnConnected, ConfirmationCraftingPart.OnConnected, GenericAssemblyStation.OnConnected and 331 more.