Class NetworkTransform
A component for syncing transforms. NetworkTransform will read the underlying transform and replicate it to clients. The replicated value will be automatically be interpolated (if active) and applied to the underlying GameObject's transform.
Inherited Members
Namespace: Unity.Netcode.Components
Assembly: Unity.Netcode.Runtime.dll
Syntax
[DisallowMultipleComponent]
[AddComponentMenu("Netcode/Network Transform")]
public class NetworkTransform : NetworkBehaviour
Fields
AuthorityMode
Declaration
[Tooltip("Selects who has authority (sends state updates) over the transform. If server (the default), then only server-side adjustments to the transform will be synchronized with clients. If owner (or client), then only the owner-side adjustments to the transform will be synchronized with both the server and other clients.")]
public NetworkTransform.AuthorityModes AuthorityMode
Field Value
Type | Description |
---|---|
NetworkTransform.AuthorityModes |
InLocalSpace
Sets whether the transform should be treated as local (true) or world (false) space.
Declaration
[Tooltip("Sets whether this transform should sync in local space or in world space")]
public bool InLocalSpace
Field Value
Type | Description |
---|---|
bool |
Remarks
This is synchronized by authority. During runtime, this should only be changed by the authoritative side. Non-authoritative instances will be overridden by the next authoritative state update.
Interpolate
When enabled (default) interpolation is applied. When disabled interpolation is disabled.
Declaration
public bool Interpolate
Field Value
Type | Description |
---|---|
bool |
Remarks
This is synchronized by authority and changes to interpolation during runtime forces a teleport/full update. During runtime, this should only be changed by the authoritative side. Non-authoritative instances will be overridden by the next authoritative state update.
OnClientRequestChange
The handler that gets invoked when server receives a change from a client. This handler would be useful for server to modify pos/rot/scale before applying client's request.
Declaration
public NetworkTransform.OnClientRequestChangeDelegate OnClientRequestChange
Field Value
Type | Description |
---|---|
NetworkTransform.OnClientRequestChangeDelegate |
PositionThreshold
The position threshold value that triggers a delta state update by the authoritative instance.
Declaration
public float PositionThreshold
Field Value
Type | Description |
---|---|
float |
Remarks
Note: setting this to zero will update position every network tick whether it changed or not.
PositionThresholdDefault
The default position change threshold value. Any changes above this threshold will be replicated.
Declaration
public const float PositionThresholdDefault = 0.001
Field Value
Type | Description |
---|---|
float |
RotAngleThreshold
The rotation threshold value that triggers a delta state update by the authoritative instance.
Declaration
[Range(1E-05, 360)]
public float RotAngleThreshold
Field Value
Type | Description |
---|---|
float |
Remarks
Minimum Value: 0.00001 Maximum Value: 360.0
RotAngleThresholdDefault
The default rotation angle change threshold value. Any changes above this threshold will be replicated.
Declaration
public const float RotAngleThresholdDefault = 0.01
Field Value
Type | Description |
---|---|
float |
ScaleThreshold
The scale threshold value that triggers a delta state update by the authoritative instance.
Declaration
public float ScaleThreshold
Field Value
Type | Description |
---|---|
float |
Remarks
Note: setting this to zero will update position every network tick whether it changed or not.
ScaleThresholdDefault
The default scale change threshold value. Any changes above this threshold will be replicated.
Declaration
public const float ScaleThresholdDefault = 0.01
Field Value
Type | Description |
---|---|
float |
SlerpPosition
When true and interpolation is enabled, this will Slerp to the target position.
Declaration
[Tooltip("When enabled the position interpolator will Slerp towards its current target position.")]
public bool SlerpPosition
Field Value
Type | Description |
---|---|
bool |
Remarks
This is synchronized by authority and only applies to position interpolation. During runtime, this should only be changed by the authoritative side. Non-authoritative instances will be overridden by the next authoritative state update.
SwitchTransformSpaceWhenParented
When enabled, the NetworkTransform will automatically handle transitioning into the respective transform space when its NetworkObject parent changes.
When parented: Automatically transitions into local space and coverts any existing pending interpolated states to local space on non-authority instances.
When deparented: Automatically transitions into world space and converts any existing pending interpolated states to world space on non-authority instances.
Set on the root NetworkTransform instance (nested NetworkTransform components should be pre-set in-editor to local space.
Declaration
public bool SwitchTransformSpaceWhenParented
Field Value
Type | Description |
---|---|
bool |
Remarks
Only works with NetworkTransform components that are not paired with a NetworkRigidbody or NetworkRigidbody2D component that is configured to use the rigid body for motion.
TickSyncChildren will automatically be set when this is enabled.
Does not auto-synchronize clients if changed on the authority instance during runtime (i.e. apply this setting in-editor).
SyncPositionX
When enabled (default), the x component of position will be synchronized by authority.
Declaration
public bool SyncPositionX
Field Value
Type | Description |
---|---|
bool |
Remarks
Changes to this on non-authoritative instances has no effect.
SyncPositionY
When enabled (default), the y component of position will be synchronized by authority.
Declaration
public bool SyncPositionY
Field Value
Type | Description |
---|---|
bool |
Remarks
Changes to this on non-authoritative instances has no effect.
SyncPositionZ
When enabled (default), the z component of position will be synchronized by authority.
Declaration
public bool SyncPositionZ
Field Value
Type | Description |
---|---|
bool |
Remarks
Changes to this on non-authoritative instances has no effect.
SyncRotAngleX
When enabled (default), the x component of rotation will be synchronized by authority.
Declaration
public bool SyncRotAngleX
Field Value
Type | Description |
---|---|
bool |
Remarks
When UseQuaternionSynchronization is enabled this does not apply. Changes to this on non-authoritative instances has no effect.
SyncRotAngleY
When enabled (default), the y component of rotation will be synchronized by authority.
Declaration
public bool SyncRotAngleY
Field Value
Type | Description |
---|---|
bool |
Remarks
When UseQuaternionSynchronization is enabled this does not apply. Changes to this on non-authoritative instances has no effect.
SyncRotAngleZ
When enabled (default), the z component of rotation will be synchronized by authority.
Declaration
public bool SyncRotAngleZ
Field Value
Type | Description |
---|---|
bool |
Remarks
When UseQuaternionSynchronization is enabled this does not apply. Changes to this on non-authoritative instances has no effect.
SyncScaleX
When enabled (default), the x component of scale will be synchronized by authority.
Declaration
public bool SyncScaleX
Field Value
Type | Description |
---|---|
bool |
Remarks
Changes to this on non-authoritative instances has no effect.
SyncScaleY
When enabled (default), the y component of scale will be synchronized by authority.
Declaration
public bool SyncScaleY
Field Value
Type | Description |
---|---|
bool |
Remarks
Changes to this on non-authoritative instances has no effect.
SyncScaleZ
When enabled (default), the z component of scale will be synchronized by authority.
Declaration
public bool SyncScaleZ
Field Value
Type | Description |
---|---|
bool |
Remarks
Changes to this on non-authoritative instances has no effect.
TickSyncChildren
When enabled, any parented NetworkObjects (children) of this NetworkObject will be forced to synchronize their transform when this NetworkObject instance sends a state update.
This can help to reduce out of sync updates that can lead to slight jitter between a parent and its child/children.
Declaration
[Tooltip("When enabled, any parented children of this instance will send a state update when this instance sends a state update. If this instance doesn't send a state update, the children will still send state updates when reaching their axis specified threshold delta. Children do not have to have this setting enabled.")]
public bool TickSyncChildren
Field Value
Type | Description |
---|---|
bool |
Remarks
- If this is set on a child and the parent does not have this set then the child will not be tick synchronized with its parent.
- If the parent instance does not send any state updates, the children will still send state updates when exceeding axis delta threshold.
- This does not need to be set on children to be applied.
UseHalfFloatPrecision
Enable this to use half float precision for position, rotation, and scale. When enabled, delta position synchronization is used.
Declaration
[Tooltip("When enabled, this will use half float precision values for position (uses delta position updating), rotation (except when Quaternion compression is enabled), and scale.")]
public bool UseHalfFloatPrecision
Field Value
Type | Description |
---|---|
bool |
Remarks
This is synchronized by authority. During runtime, this should only be changed by the authoritative side. Non-authoritative instances will be overridden by the next authoritative state update.
UseQuaternionCompression
Enabled this on the authority side for quaternion compression
Declaration
[Tooltip("When enabled, this uses a smallest three implementation that reduces full Quaternion updates down to the size of an unsigned integer (ignores half float precision settings).")]
public bool UseQuaternionCompression
Field Value
Type | Description |
---|---|
bool |
Remarks
This has a lower precision than half float precision. Recommended only for low precision scenarios. UseHalfFloatPrecision provides better precision at roughly half the cost of a full quaternion update. This is synchronized by authority. During runtime, this should only be changed by the authoritative side. Non-authoritative instances will be overridden by the next authoritative state update.
UseQuaternionSynchronization
Enable this on the authority side for quaternion synchronization
Declaration
[Tooltip("When enabled, this will synchronize the full Quaternion (i.e. all Euler rotation axis are updated if one axis has a delta)")]
public bool UseQuaternionSynchronization
Field Value
Type | Description |
---|---|
bool |
Remarks
This is synchronized by authority. During runtime, this should only be changed by the authoritative side. Non-authoritative instances will be overridden by the next authoritative state update.
UseUnreliableDeltas
Enabled by default. When set (enabled by default), NetworkTransform will send common state updates using unreliable network delivery to provide a higher tolerance to poor network conditions (especially packet loss). When disabled, all state updates are sent using a reliable fragmented sequenced network delivery.
Declaration
[Tooltip("When set, NetworkTransform will send common state updates using unreliable network delivery to provide a higher tolerance to poor network conditions (especially packet loss). When disabled, all state updates are sent using reliable fragmented sequenced network delivery.")]
public bool UseUnreliableDeltas
Field Value
Type | Description |
---|---|
bool |
Remarks
The following more critical state updates are still sent as reliable fragmented sequenced:
- The initial synchronization state update
- The teleporting state update.
- When using half float precision and the
NetworkDeltaPosition
delta exceeds the maximum delta forcing the axis in question to be collapsed into the core base position, this state update will be sent as reliable fragmented sequenced.
In order to preserve a continual consistency of axial values when unreliable delta messaging is enabled (due to the possibility of dropping packets), NetworkTransform instances will send 1 axial frame synchronization update per second (only for the axis marked to synchronize are sent as reliable fragmented sequenced) as long as a delta state update had been previously sent. When a NetworkObject is at rest, axial frame synchronization updates are not sent.
m_AddLogEntry
Declaration
protected NetworkTransform.AddLogEntryHandler m_AddLogEntry
Field Value
Type | Description |
---|---|
NetworkTransform.AddLogEntryHandler |
m_CachedNetworkManager
Internally used by NetworkTransform to keep track of the NetworkManager instance assigned to this this NetworkBehaviour derived class instance.
Declaration
protected NetworkManager m_CachedNetworkManager
Field Value
Type | Description |
---|---|
NetworkManager |
Properties
CanCommitToTransform
Used to determine who can write to this transform. Server only for this transform. Changing this value alone in a child implementation will not allow you to create a NetworkTransform which can be written to by clients. See the ClientNetworkTransform Sample in the package samples for how to implement a NetworkTransform with client write support. If using different values, please use RPCs to write to the server. Netcode doesn't support client side network variable writing
Declaration
public bool CanCommitToTransform { get; protected set; }
Property Value
Type | Description |
---|---|
bool |
PositionInLocalSpace
Declaration
protected bool PositionInLocalSpace { get; }
Property Value
Type | Description |
---|---|
bool |
RotationInLocalSpace
Declaration
protected bool RotationInLocalSpace { get; }
Property Value
Type | Description |
---|---|
bool |
Methods
ApplyAuthoritativeState()
Applies the authoritative state to the transform
Declaration
protected void ApplyAuthoritativeState()
Awake()
Create interpolators when first instantiated to avoid memory allocations if the associated NetworkObject persists (i.e. despawned but not destroyed or pools)
Declaration
protected virtual void Awake()
GetHalfPositionState()
Declaration
protected NetworkDeltaPosition GetHalfPositionState()
Returns
Type | Description |
---|---|
NetworkDeltaPosition |
GetScale(bool)
Helper method that returns the scale of the transform.
Declaration
public Vector3 GetScale(bool getCurrentState = false)
Parameters
Type | Name | Description |
---|---|---|
bool | getCurrentState | Authority always returns the space relative transform scale (whether true or false). Non-authority: When false (default): returns the space relative transform scale When true: returns the authority scale from the most recent state update. |
Returns
Type | Description |
---|---|
Vector3 |
Remarks
When invoked on the non-authority side: If getCurrentState is true then it will return the most current authority scale from the most recent state update. This can be useful if interpolation is enabled and you need to determine the final target scale. When invoked on the authority side: It will always return the space relative scale.
GetSpaceRelativePosition(bool)
Helper method that returns the space relative position of the transform.
Declaration
public Vector3 GetSpaceRelativePosition(bool getCurrentState = false)
Parameters
Type | Name | Description |
---|---|---|
bool | getCurrentState | Authority always returns the space relative transform position (whether true or false). Non-authority: When false (default): returns the space relative transform position When true: returns the authority position from the most recent state update. |
Returns
Type | Description |
---|---|
Vector3 |
Remarks
If InLocalSpace is true then it returns the transform.localPosition If InLocalSpace is false then it returns the transform.position When invoked on the non-authority side: If getCurrentState is true then it will return the most current authority position from the most recent state update. This can be useful if interpolation is enabled and you need to determine the final target position. When invoked on the authority side: It will always return the space relative position.
GetSpaceRelativeRotation(bool)
Helper method that returns the space relative rotation of the transform.
Declaration
public Quaternion GetSpaceRelativeRotation(bool getCurrentState = false)
Parameters
Type | Name | Description |
---|---|---|
bool | getCurrentState | Authority always returns the space relative transform rotation (whether true or false). Non-authority: When false (default): returns the space relative transform rotation When true: returns the authority rotation from the most recent state update. |
Returns
Type | Description |
---|---|
Quaternion |
Remarks
If InLocalSpace is true then it returns the transform.localRotation If InLocalSpace is false then it returns the transform.rotation When invoked on the non-authority side: If getCurrentState is true then it will return the most current authority rotation from the most recent state update. This can be useful if interpolation is enabled and you need to determine the final target rotation. When invoked on the authority side: It will always return the space relative rotation.
GetStateId(ref NetworkTransformState)
Declaration
protected int GetStateId(ref NetworkTransform.NetworkTransformState state)
Parameters
Type | Name | Description |
---|---|---|
NetworkTransform.NetworkTransformState | state |
Returns
Type | Description |
---|---|
int |
GetTickLatency()
Returns the number of ticks (fractional) a client is latent relative to its current RTT.
Declaration
public static float GetTickLatency()
Returns
Type | Description |
---|---|
float |
GetTickLatencyInSeconds()
Returns the tick latency in seconds (typically fractional)
Declaration
public static float GetTickLatencyInSeconds()
Returns
Type | Description |
---|---|
float |
Initialize()
Initializes NetworkTransform when spawned and ownership changes.
Declaration
protected void Initialize()
InternalOnNetworkPostSpawn()
For dynamically spawned NetworkObjects, when the non-authority instance's client is already connected and the SynchronizeState is still pending synchronization then we want to finalize the synchornization at this time.
Declaration
protected override void InternalOnNetworkPostSpawn()
Overrides
InternalOnNetworkSessionSynchronized()
Handle applying the synchronization state once everything has spawned. The first NetowrkTransform handles invoking this on any other nested NetworkTransform.
Declaration
protected override void InternalOnNetworkSessionSynchronized()
Overrides
IsServerAuthoritative()
Method to determine if this NetworkTransform instance is owner or server authoritative.
Declaration
public bool IsServerAuthoritative()
Returns
Type | Description |
---|---|
bool | true or false |
Remarks
When using a DistributedAuthority NetworkTopology, this will always be viewed as a Owner authoritative motion model.
OnAuthorityPushTransformState(ref NetworkTransformState)
Invoked just prior to being pushed to non-authority instances.
Declaration
protected virtual void OnAuthorityPushTransformState(ref NetworkTransform.NetworkTransformState networkTransformState)
Parameters
Type | Name | Description |
---|---|---|
NetworkTransform.NetworkTransformState | networkTransformState | the state being pushed |
Remarks
This is useful to know the exact position, rotation, or scale values sent to non-authoritative instances. This is only invoked on the authoritative instance.
OnBeforeUpdateTransformState()
Declaration
protected virtual void OnBeforeUpdateTransformState()
OnDestroy()
Invoked when the GameObject the NetworkBehaviour is attached to is destroyed. If you override this, you must always invoke the base class version of this OnDestroy() method.
Declaration
public override void OnDestroy()
Overrides
OnFixedUpdate()
When paired with a NetworkRigidbody and NetworkRigidbody.UseRigidBodyForMotion is enabled, this will be invoked during NetworkRigidbody.FixedUpdate.
Declaration
public virtual void OnFixedUpdate()
OnGainedOwnership()
In client-server contexts, this method is invoked on both the server and the local client of the owner when NetworkObject ownership is assigned.
In distributed authority contexts, this method is only invoked on the local client that has been assigned ownership of the associated NetworkObject.
Declaration
public override void OnGainedOwnership()
Overrides
OnInitialize(ref NetworkTransformState)
Invoked when first spawned and when ownership changes.
Declaration
protected virtual void OnInitialize(ref NetworkTransform.NetworkTransformState replicatedState)
Parameters
Type | Name | Description |
---|---|---|
NetworkTransform.NetworkTransformState | replicatedState | the current NetworkTransform.NetworkTransformState after initializing |
OnInitialize(ref NetworkVariable<NetworkTransformState>)
This method is only invoked by the owner Use: OnInitialize(ref NetworkTransformState replicatedState) to be notified on all instances
Declaration
protected virtual void OnInitialize(ref NetworkVariable<NetworkTransform.NetworkTransformState> replicatedState)
Parameters
Type | Name | Description |
---|---|---|
NetworkVariable<NetworkTransform.NetworkTransformState> | replicatedState |
OnIsServerAuthoritative()
Determines whether the NetworkTransform is Server or Owner based on the AuthorityMode property. You can override this method to control this logic.
Declaration
protected virtual bool OnIsServerAuthoritative()
Returns
Type | Description |
---|---|
bool | true or false |
OnLostOwnership()
In client-server contexts, this method is invoked on the local client when it loses ownership of the associated NetworkObject and on the server when any client loses ownership.
In distributed authority contexts, this method is only invoked on the local client that has lost ownership of the associated NetworkObject.
Declaration
public override void OnLostOwnership()
Overrides
OnNetworkDespawn()
Gets called when the NetworkObject gets despawned. This method runs both client and server side.
Declaration
public override void OnNetworkDespawn()
Overrides
OnNetworkObjectParentChanged(NetworkObject)
Gets called when the parent NetworkObject of this NetworkBehaviour's NetworkObject has changed.
Declaration
public override void OnNetworkObjectParentChanged(NetworkObject parentNetworkObject)
Parameters
Type | Name | Description |
---|---|---|
NetworkObject | parentNetworkObject | the new NetworkObject parent |
Overrides
Remarks
When not using a NetworkRigidbody and using an owner authoritative motion model, you can
improve parenting transitions into and out of world and local space by:
- Disabling SyncOwnerTransformWhenParented
- Enabling AllowOwnerToParent
- Enabling SwitchTransformSpaceWhenParented
-- Note: This handles changing from world space to local space for you.
When these settings are applied, transitioning from: - World space to local space (root-null parent/null to NetworkObject parent)
- Local space back to world space (NetworkObject parent to root-null parent)
- Local space to local space (NetworkObject parent to NetworkObject parent) Will all smoothly transition while interpolation is enabled. (Does not work if using a Rigidbody or Rigidbody2D for motion)
When a parent changes, non-authoritative instances should:
- Apply the resultant position, rotation, and scale from the parenting action.
- Clear interpolators (even if not enabled on this frame)
- Reset the interpolators to the position, rotation, and scale resultant values.
This prevents interpolation visual anomalies and issues during initial synchronization
OnNetworkSpawn()
Gets called when the NetworkObject gets spawned, message handlers are ready to be registered, and the network is set up.
Declaration
public override void OnNetworkSpawn()
Overrides
OnNetworkTransformStateUpdated(ref NetworkTransformState, ref NetworkTransformState)
Invoked on the non-authoritative side when the NetworkTransformState has been updated
Declaration
protected virtual void OnNetworkTransformStateUpdated(ref NetworkTransform.NetworkTransformState oldState, ref NetworkTransform.NetworkTransformState newState)
Parameters
Type | Name | Description |
---|---|---|
NetworkTransform.NetworkTransformState | oldState | the previous NetworkTransform.NetworkTransformState |
NetworkTransform.NetworkTransformState | newState |
OnOwnershipChanged(ulong, ulong)
Invoked on all clients. Override this method to be notified of any ownership changes (even if the instance was neither the previous or newly assigned current owner).
Declaration
protected override void OnOwnershipChanged(ulong previous, ulong current)
Parameters
Type | Name | Description |
---|---|---|
ulong | previous | the previous owner |
ulong | current | the current owner |
Overrides
OnSynchronize<T>(ref BufferSerializer<T>)
This is invoked when a new client joins (server and client sides) Server Side: Serializes as if we were teleporting (everything is sent via NetworkTransformState) Client Side: Adds the interpolated state which applies the NetworkTransformState as well
Declaration
protected override void OnSynchronize<T>(ref BufferSerializer<T> serializer) where T : IReaderWriter
Parameters
Type | Name | Description |
---|---|---|
BufferSerializer<T> | serializer |
Type Parameters
Name | Description |
---|---|
T |
Overrides
Remarks
If a derived class overrides this, then make sure to invoke this base method!
OnTransformUpdated()
Declaration
protected virtual void OnTransformUpdated()
OnUpdate()
Declaration
public virtual void OnUpdate()
Remarks
If you override this method, be sure that:
- Non-authority always invokes this base class method.
SetMaxInterpolationBound(float)
Will set the maximum interpolation boundary for the interpolators of this NetworkTransform instance. This value roughly translates to the maximum value of 't' in Lerp(Vector3, Vector3, float) and Lerp(Quaternion, Quaternion, float) for all transform elements being monitored by NetworkTransform (i.e. Position, Scale, and Rotation)
Declaration
public void SetMaxInterpolationBound(float maxInterpolationBound)
Parameters
Type | Name | Description |
---|---|---|
float | maxInterpolationBound | Maximum time boundary that can be used in a frame when interpolating between two values |
SetState(Vector3?, Quaternion?, Vector3?, bool)
Directly sets a state on the authoritative transform. Owner clients can directly set the state on a server authoritative transform This will override any changes made previously to the transform This isn't resistant to network jitter. Server side changes due to this method won't be interpolated. The parameters are broken up into pos / rot / scale on purpose so that the caller can perturb just the desired one(s)
Declaration
public void SetState(Vector3? posIn = null, Quaternion? rotIn = null, Vector3? scaleIn = null, bool teleportDisabled = true)
Parameters
Type | Name | Description |
---|---|---|
Vector3? | posIn | |
Quaternion? | rotIn | |
Vector3? | scaleIn | new scale to scale to. Can be null |
bool | teleportDisabled | When true (the default) the NetworkObject will not be teleported and, if enabled, will interpolate. When false the NetworkObject will teleport/apply the parameters provided immediately. |
Exceptions
Type | Condition |
---|---|
Exception |
Teleport(Vector3, Quaternion, Vector3)
Teleport an already spawned object to the given values without interpolating.
Declaration
public void Teleport(Vector3 newPosition, Quaternion newRotation, Vector3 newScale)
Parameters
Type | Name | Description |
---|---|---|
Vector3 | newPosition | |
Quaternion | newRotation | |
Vector3 | newScale | new scale to scale to. |
Remarks
This is intended to be used on already spawned objects, for setting the position of a dynamically spawned object just apply the transform values prior to spawning.
With player objects, override the OnNetworkSpawn() method and have the authority make adjustments to the transform prior to invoking base.OnNetworkSpawn.
Exceptions
Type | Condition |
---|---|
Exception |