NetworkEntity
A class in Root.Township, Alta.Networking.
A networked object: anything the server spawns, saves and syncs to players, including embedded parts of a prefab. Both sides; the server owns it. Get one from a component with GetComponent<NetworkEntity>() or a behaviour's Entity.
- Listed in Networking and servers
- Inherits or implements
MonoBehaviour,IChunkedEntity,IEntitySerialized,INetworkEntity - Derived types
NetworkEntityModifiers,Player,PositionedNetworkPrefab - Nested types
SyncPriorityModifiers - Attributes
DisallowMultipleComponent - Documented in NetworkEntity
Constructors
| Member | What it is |
|---|---|
protected NetworkEntity() | Unity makes components itself; use AddComponent or spawn a prefab instead of new. |
Fields
| Member | What it is |
|---|---|
OneTimeEvent<NetworkEntityHandler> InitializationFinished | A one-time event raised after Initialize. Handlers added later run straight away. |
21 private and internal fields
| Member | What it is |
|---|---|
private Transform cachedTransform | Cached transform, filled on first use by Transform and FramePosition. |
private Chunker chunker | Backing field for Chunker, created in the constructor. |
private ImpactTool commonImpactTool | The ImpactTool on the same object, found in the editor; backing field for CommonImpactTool. |
private Interactable commonInteractable | The Interactable on the same object, found in the editor; backing field for CommonInteractable. |
private Pickup commonPickup | The Pickup on the same object, found in the editor; backing field for CommonPickup. |
private int embeddedId | Backing field for EmbeddedId: the entity's index among the embedded child entities of its prefab. |
private Func<NetworkEntity, Chunk> getPositionChunk | Function behind PositionChunk. By default it walks up the chunking parents and uses the top one's chunk. |
private int hash | Backing field for Hash, validated in OnValidate. |
private bool hasNetworkBehaviours | Set in the editor when the object has any INetworkEntityBehaviour; InitializeAsServer skips the behaviours when false. |
private bool isInitializedAsServer | Stops InitializeAsServer from running twice. |
private bool isSendingMessages | Backing field for IsSendingMessages. |
private int lastFrame | Frame number when lastFramePosition was last read; lets FramePosition read the transform once per frame. |
private Vector3 lastFramePosition | Position cached for the current frame by FramePosition. |
private static readonly Logger logger | NLog logger for this class. |
private EntityMessageHandler messageHandler | Backing field for MessageHandler, created on first use. |
private MethodSync moveEntity | Method sync for MoveEntity messages, used by ForcePositionSync to send the position to the entity's chunks. |
private MonoBehaviour[] networkEntityBehaviours | Every INetworkEntityBehaviour on the object, found in the editor; these get the initialize, connect and disconnect calls. |
private NetworkPrefab prefab | The NetworkPrefab on the same object; backing field for Prefab. |
private static readonly List<INetworkSerialized> serializedBehaviours | Static scratch list used by CreateSerializer while it collects the serialized behaviours. |
private EntitySerializer serializer | Backing field for Serializer; null when no behaviour is serialized. |
private int syncPriority | Base sync priority (default 10). SyncPriority lowers it by 5 while any priority modifier, such as docked or interacted, is set. |
Properties
| Member | What it is |
|---|---|
int ChildCount { get; } | How many entities have this one as their ChunkingParent. |
IEnumerable<NetworkEntity> Children { get; } | Entities that have this one as their ChunkingParent, such as docked items and a bag's contents. |
Chunk Chunk { get; set; } | The chunk the entity is in. Setting it moves it there; on the server this is ignored while it has a ChunkingParent. |
NetworkEntity ChunkingParent { get; set; } | The entity this one rides with (a dock's owner, a part's structure). It takes that parent's chunk. |
ImpactTool CommonImpactTool { get; } | The ImpactTool on the same object, cached at bake time, or null. |
Interactable CommonInteractable { get; } | The Interactable on the same object, cached at bake time, or null. |
Pickup CommonPickup { get; } | The Pickup on the same object, cached at bake time, or null. |
NetworkEntity.SyncPriorityModifiers CurrentPriorityModifiers { get; set; } | Flags that raise sync priority. DockedOrInteracted is set while held or docked and lowers SyncPriority by 5. |
INetworkScene EditorSafeScene { get; } | The entity's scene, or in the editor outside play mode, the first NetworkScene found. |
int EmbeddedId { get; set; } | Its index in its prefab's embedded entity list. |
Vector3 FramePosition { get; } | transform.position, cached once per frame. Cheap in hot loops. |
uint Hash { get; } | The entity's own hash inside its prefab, set in the editor. Used to match embedded entities when a save loads. |
uint Identifier { get; private set; } | The runtime id used by messages and commands. Changes on every spawn or chunk load, so never save it. |
bool IsBeingDestroyed { get; set; } | True once a destroy or unload has started. Check it in delayed callbacks. |
bool IsInitialized { get; private set; } | True after Initialize has run. |
bool IsOnClientOrLocalTest { get; } | True on a client once initialized, or in a local test. False on a dedicated server. |
bool IsSendingMessages { get; set; } | When false, messages from this entity are dropped with a warning. |
bool IsSerialized { get; } | True if the entity has any INetworkSerialized behaviours and so a Serializer. |
bool IsSerializerAuthoritative { get; } | Whether this side owns the entity's serialized state. Throws if there's no serializer. |
EntityMessageHandler MessageHandler { get; } | Sends this entity's messages to its players or to the server. Created on first use. |
string OriginalName { get; set; } | The object's name before Initialize prefixed it with the id. |
NetworkEntity Parent { get; private set; } | For an embedded entity, the prefab entity it's part of. Null otherwise. Not the same as ChunkingParent. |
IEnumerable<IPlayer> PlayersSpawnedFor { get; } | Server: the players whose game currently has this entity. |
int PlayersSpawnedForCount { get; } | Server: how many players currently have this entity. |
Chunk PositionChunk { get; } | The chunk its position is written against: the chunking parent's, or its own. Populations can override how it's found. |
NetworkPrefab Prefab { get; } | The NetworkPrefab on the same object. Null for embedded entities. |
NetworkEntity PrefabRoot { get; private set; } | The top entity of the prefab this belongs to. Itself for a prefab, the prefab entity for an embedded part. |
string SafeName { get; } | id - OriginalName, handy for logs. |
INetworkScene Scene { get; protected set; } | The network scene the entity belongs to. |
EntitySerializer Serializer { get; } | The state sync for its INetworkSerialized behaviours, or null if it has none. |
static int SpawnedCount { get; private set; } | Static. Live NetworkEntity components in the process, embedded parts included. |
SpawnManager Spawner { get; private set; } | The scene's spawn manager, used to spawn and destroy entities. |
SpawnIndex SpawnIndex { get; } | A spawn counter used to ignore stale destroy messages for an id that has been reused. |
static ConnectionChannel SyncChannel { get; set; } | Static. The connection channel entity messages go on; swapped temporarily while chunks are synced. |
int SyncPriority { get; } | Lower syncs first when a chunk is sent to a player. Set per prefab (10 by default), 5 less while held or docked. |
Transform Transform { get; } | The entity's transform, cached. |
protected Chunker Chunker { get; } | Protected. The helper that tracks this entity's chunk, chunking parent, children and the players it's spawned for. |
1 private and internal property
Events
| Member | What it is |
|---|---|
event ChunkEventHandler AddedToChunk | Raised when the entity enters a chunk. |
event NetworkEntityHandler ChildAdded | Raised when another entity takes this one as its ChunkingParent. |
event NetworkEntityHandler ChildRemoved | Raised when a child entity stops riding on this one. |
event EntityDespawnedHandler DestroyedByScene | Raised when the spawner destroys or unloads the entity, with whether it was an unload. Cleared after it fires. |
event ParentChangedHandler ParentChanged | Raised when the ChunkingParent changes, with the old and new parent. |
event ChunkEventHandler RemovedFromChunk | Raised when the entity leaves a chunk. |
Methods
| Member | What it is |
|---|---|
void DelayedSceneDestroy() | Calls SceneDestroy 0.1 seconds later. |
void EditorEvaluateChunk(FastChunkLookup chunkLookup) | Editor tool: puts the entity in a chunk using a prebuilt chunk lookup. |
void EmbededdedInitialize(NetworkEntity parent) | Sets the parent prefab entity for an embedded entity and makes that parent its ChunkingParent and PrefabRoot. |
void EvaluateChunk(bool isLoggingOnFailure = true) | Server: moves the entity to the chunk that holds its position. Can destroy it if no chunk does. |
void ForcePositionSync() | Server: re-evaluates its chunk and sends its position and rotation to every player who has it. Use after moving it. |
void ForceSetIsInitialized() | Marks the entity initialized without running Initialize. |
T GetComponentOnEntity<T>() | The first component of that type in the entity's behaviour list. Faster than GetComponent but only finds network behaviours. |
IEnumerable<T> GetComponentsOnEntity<T>() (iterator) | Every component of that type in the entity's behaviour list. |
virtual void Initialize(INetworkScene scene, NetworkEntity parent, uint identifier, uint[] embeddedIdentifiers, bool isInitializingBehaviours) | Gives the entity its scene and id, renames it to id - name, builds its serializer and initializes embedded entities and behaviours. |
void InitializeAsPlayer(PlayerController player) | Hands sync authority for this entity to a player's body. Called when a PlayerController links to its player. |
void InitializeAsServer(SpawnData spawnData) | Server: makes the server authoritative and calls InitializeAsServer on every behaviour. Runs once; later calls return early. |
void InitializeBehaviours() | Calls Initialize on every behaviour in the entity's list, logging any exception. |
void InitializeWithChildrenAsServer(SpawnData spawnData) | Server: runs InitializeAsServer on this entity and then on every child, recursively. |
bool IsSpawnedFor(Player player) | Server: whether that player's game currently has this entity. |
virtual void OnConnected(Player player) | Server: calls OnConnected on every behaviour when the entity is sent to a player. |
void OnDestroyedByScene(bool isUnload) | Called by the spawner on destroy or unload: frees the serializer and raises DestroyedByScene. |
virtual void OnDisconnected(Player player) | Server: calls OnDisconnected on every behaviour when a player loses the entity. |
void OnValidate() | Editor: makes sure the entity has a hash. |
void OwnAsSinglePlayer() | Not implemented; throws. |
void PrepareForDestroy() | Server: frees the entity's id link before destroy. Logs an error instead for a child still attached to a parent in a chunk. |
void ReplaceWith(NetworkEntity entity, ReplaceAvoidFlags replaceAvoidFlags = 0) | Copies this entity's position, chunk and component state (through IEntityReplaceHandlers) onto another entity. Flags skip position or chunk. |
void SceneDestroy() | Server: destroys the entity properly, on every client too. Does nothing on clients. |
void SetupGetPositionChunk(Func<NetworkEntity, Chunk> newMethod) | Sets how PositionChunk is worked out. With no argument, uses the chunking parent's chunk or its own. |
void SetupGetPositionChunk() | Sets how PositionChunk is worked out. With no argument, uses the chunking parent's chunk or its own. |
NetworkEntity SpawnAndReplaceWith(NetworkPrefab prefab, bool isDestroying = true) | Server: spawns another prefab in its place with this one's position, state, chunk and chunking parent, then destroys this one by default. |
NetworkEntity SpawnAndReplaceWith(uint prefabHash, bool isDestroying = true) | Server: spawns another prefab in its place with this one's position, state, chunk and chunking parent, then destroys this one by default. |
AltaCoroutine StartCoroutine(IEnumerator enumerator) | Starts an AltaCoroutine that stops when the entity is destroyed by the scene. Hides the Unity method. |
protected virtual void Awake() | Sets PrefabRoot to itself until initialized and counts the entity in SpawnedCount. |
9 private and internal methods
| Member | What it is |
|---|---|
private bool CheckForNetworkBehaviour() | Editor validation check that sets hasNetworkBehaviours: true if the object has any INetworkEntityBehaviour. |
private void CreateSerializer(MonoBehaviour[] behaviours) | Called from Initialize: builds an EntitySerializer from the behaviours that implement INetworkSerialized and registers it with the scene. |
private void OnChildAdded(NetworkEntity child) | Raises ChildAdded when another entity starts using this one as its chunking parent. |
private void OnChildRemoved(NetworkEntity child) | Raises ChildRemoved when another entity stops using this one as its chunking parent. |
private void OnDestroy() | Lowers SpawnedCount, unlinks the entity from its spawner if it wasn't destroyed through the scene, and releases the serializer arrays. |
private void OnDisable() | Logs an error if the entity is disabled while still active in the hierarchy and not marked IsBeingDestroyed. |
private void OnInitialize() | Runs at the end of the first Initialize and sets up the moveEntity method sync. |
private void Alta.Networking.IChunkedEntity.OnParentChanged(NetworkEntity oldParent, NetworkEntity parent) | Called by the chunker when the chunking parent changes: raises ParentChanged, then ChildRemoved on the old parent and ChildAdded on the new one. |
private void SerializeMove(IPlayer player, Stream stream) | Writes or reads the entity's position (chunk-relative) and compressed rotation for a move message, then calls Moved on every IUpdateOnMove. |
Used in
Members of other types that take, return or hold a NetworkEntity:
EffectHandler.entity, EffectHandler.Entity, PlayerEffectController.Initialize, ForgedPoint.Entity, ForgedPointCollection.Alta.Networking.IEntityReplaceHandler.Entity, ForgedPointCollection.ReplacedWith, MeltingModel.SceneDestroy, Recycler.affecting, Smelter.ReleaseSmoke, ClusterGenerator.PositionChild, StaticClusterGenerator.Generate, HandTargetHandler.entity, CaveLayerStaticObject.RemoveRenderers, CaveLayerStreamer.layerEntity, Chunk.SerializeChunkAndPosition, Chunk.SerializePosition, ChunkConnections.RemoveAdjacent, ChunkEntityManager.Add, ChunkEntityManager.Added, ChunkEntityManager.Cache, ChunkEntityManager.CompareEntitiesPosition, ChunkEntityManager.CompareFeet, ChunkEntityManager.Contains, ChunkEntityManager.EnteredWhileUnloaded, ChunkEntityManager.entities, ChunkEntityManager.Entities, ChunkEntityManager.HandleChunkNotLoaded, ChunkEntityManager.OnAdded, ChunkEntityManager.OnRemoved, ChunkEntityManager.Remove, ChunkEntityManager.Removed, ChunkEntityManager.Sort, ChunkEntityManager.tempSort, ChunkEntityManager.tempSortMap, ChunkPositionSurface.Destroyed, ChunkSync.cachedEntities, DynamicChunkContentManager.GetEmbeddedSave, DynamicChunkContentManager.LoadSerializeEntity, DynamicChunkContentManager.UnloadSingle, ICaveLayer.Entity, LocationChunk.SerializePosition, SavableSavedDynamicObject.Spawn, SavableSavedDynamicObject.SpawnOwned, SavedDynamicObject.GetPositionlessSaveOf, SavedDynamicObject.GetSaveOf, SavedDynamicObject.Spawn, SavedDynamicObject.SpawnOwned, StreamerHelper.DelayDestroy, StreamerHelper.LoadSetupRecursive, StreamerHelper.PostToPlayer, StreamerHelper.SerializePrefab, StreamerHelper.WritePositionlessPrefab, AltaSelection.Current, EntityInfo.op_Implicit, Inventory.AddChildren, NetworkEntityInfo.op_Implicit, PrefabInfoDump.NetworkEntityInfoDump.op_Implicit, SpawnCommandModule.Spawn, SpawnCommandModule.SpawnFull, WackyCommandModule.ReplaceEntity and 537 more.