CoherenceSync

CoherenceSync

CoherenceSync is a component that should be attached to the root of every networked GameObject. It may be your player, an NPC or an inanimate object such as a ball, a projectile or a banana. Anything that needs to be synchronized over the network and turned into an Entity.Once a CoherenceSync is added to a prefab, you can select which individual public properties you would like to sync across the network, expose methods as Commands, and configure other network-related properties.

The top of a CoherenceSync inspector

Synced Variables

To start syncing members of a component, open the Configure window that you can access from the CoherenceSync's Inspector.Any components attached to the GameObject with CoherenceSync that have public fields or properties will be shown here and can be synced across the network.To start syncing a member, just tick the checkbox next to it. Optionally, you can also choose how it is interpolated using the control to its right.

Configure window

Commands

Commands are public methods that can be executed remotely. In other networking frameworks they are often referred to as RPCs (Remote Procedure Calls).To mark a method as a Command, you can do it from the Configure window in the same way described above when syncing properties by going to the second tab labelled "Commands".For more info, refer to the page about messaging with Commands.

Component Actions

When a networked object is instantiated, other Clients will see it, but won't have authority over its state. It is often important to ensure that some components behave differently for Clients that don't have authority over the entity.

To quickly achieve this, you can leverage Component Actions, which are located in the Components tab of the Configure window:

The sections above describe UI-based workflows to sync variables and commands. We also offer a code-based workflow, which leverages [Sync] and [Command] C# attributes directly from within code.

(You can notice in the screenshot above how the isBeingCarried property is synced in code, and displays the [Sync] tag in front of its name.)

The two workflows can be used together, even on the same Prefab!

You can also create your own, custom Component Actions.

Inspector Options

Simulate In

Defines which type of Client or Simulator can have authority over this Entity.

  • Client Side - The Entity is by default owned by the Client that spawns it. It can be also owned by a Simulator.

  • Server Side - The Entity can't be owned by a normal Client, but only by a Simulator.

  • Server Side With Client Input - This automatically adds a CoherenceInput component. Ownership is split: a Simulator holds State Authority, while a Client has Input Authority. See Server Authoritative setup for more info.

When a Client disconnects, all the Network Entities created by that Client are usually destroyed. If you want any Entity to stay after the owner disconnects, you need to set Entity lifetime type of that Prefab to Persistent.

  • Session Based - the Entity will be removed on all other Clients, when the owner Client disconnects.

  • Persistence - Entities with this option will persist as long as the Replication Server is running. For more details, see Configuring persistence.

Orphaned Entities

By making the GameObject persistent, you ensure that it remains in the game world even after its owner disconnects. But once the GameObject has lost its owner, it will remain frozen in place because no Client is allowed to update or delete it. This is called an orphaned GameObject.

In order to make the orphaned GameObject interactive again, another Client needs to take ownership of it. To do this, one can use APIs (specifically, Adopt()) or – more conveniently – enable Auto-adopt orphan on the Prefab.

  • Allow Duplicates - multiple copies of this object can be instantiated over the network. This is typical for bullets, spell effects, RTS units, and similar repeated Entities.

  • No Duplicates - ensures objects are not duplicated by assigning them a Unique ID.

    • Manual Unique ID - You can set the Unique ID manually in the Prefab, only one Prefab instance will be allowed at runtime, any other instance created with the same UUID will be destroyed.

    • Prefab Instance Unique ID - When creating a Prefab instance in the Scene at Editor time, a special Prefab Instance Unique ID is assigned, if the manual UUID is blank, the UUID assigned at runtime will be the Prefab Instance ID.

Prefab Instance with a Unique ID

Manual ID vs. Prefab Instance ID

To understand the difference between these two IDs, consider the following use cases:

Manager: If your game has a Prefab of which there can only be 1 in-game instance at any time (such as a Game Manager), assign an ID manually on the Prefab asset.

Multiple interactable scene objects: If you have several instances of a given Prefab, but each instance must be unique (such as doors, elevators, pickups, traps, etc.), each instance created in Editor time will have a auto-generated Prefab Instance Unique ID. This will ensure that when 2 players come online, they only bring one copy of any given door/trap/pickup, but each of them still replicates its state across the network to all Clients currently in the same scene.

When you create a networked GameObject, you automatically become the owner of that GameObject. That means only you are allowed to update its values, or destroy it. But sometimes it is necessary to pass ownership from one Client to another. For example, you could snatch the football in a soccer game or throw a mind control spell in a strategy game. In these cases, you will need to transfer ownership over these Entities from one Client to another.

When an authority transfer request is performed, an Entity can be set up to respond in different ways to account for different gameplay cases:

  • Not Transferable - Authority requests will always fail. This is a typical choice for player characters.

  • Steal - Authority requests always succeed.

  • Request - This option is intended for conditional transfers. The owner of an Entity can reply to an authority request by either accepting or denying it.

    • Approve Requests - The requests will succeed even if no event listener is present.

Note that for Request, a listener to the event OnAuthorityRequested needs to be provided in code. If not present, the optional parameter Approve Requests can be used as a fallback. This is only useful in corner cases where the listener is added and removed at runtime. In general, you can simply set the transfer style to Steal and all requests will automatically succeed.

Transfer requests API

Any Client or Simulator can request ownership by invoking the RequestAuthority() method on the CoherenceSync component of a Network Entity:

someGameObject.GetComponent<CoherenceSync>().RequestAuthority();

A request will be sent to the Entity's current owner. They will then accept or deny the request, and complete the transfer. If the transfer succeeds, the previous owner is no longer allowed to update or destroy the Entity.

Advanced Inspector Options

Interpolate On

The Unity event functions that should be used to perform interpolation.

Update / LateUpdate / FixedUpdate

Bindings will be updated with interpolated values during every Update / LateUpdate / FixedUpdate event.

Combination

You can combine any of the above, so that bindings are updated in more than one Unity callback

Nothing

bindings will completely stop receiving new values because interpolation is fully disabled

If you are using Rigidbody for movement of a GameObject, it is recommended to set Interpolate On to FixedUpdate. Also, to achieve completely smooth movement, Rigidbody interpolation should be enabled and you should avoid setting the position of a GameObject directly using Transform.position or Rigidbody.position.

Rigidbody Update Mode

Specifies the means by which networked entities that have a Rigidbody or Rigidbody2D attached should be updated.

Direct (Default)

directly sets the Rigidbody.position and Rigidbody.rotation properties.

Use this if you're parenting entities with and want replicated entities to have kinetic rigidbodies.

Can be used with CoherenceNode and parenting.

Interpolated

Uses the Rigidbody.MovePosition / Rigidbody.MoveRotation methods to maintain the physical state of the replicated rigidbody.

Use this if you need replicated entities to have and linear velocity and angular velocity replicated.

Note: does not support using CoherenceNode or parenting since the coherence position and rotation are derived from the rigidbody and so are always in world position.

Manual

Raises the OnRigidbody3DPositionUpdate and OnRigidbody3DRotationUpdate (or the 2D variants if a Rigidbody2D is attached) events with world position and world rotation passed as event handler arguments.

Use this is you want manual control of the update of the state of the networked object's Rigidbody.

Note: does not support using CoherenceNode or parenting since the coherence position and rotation are derived from the rigidbody and so are always in world position.

Is Global

When enabled, the entity is visible to global queries.

Tag

Adding a tag makes this object visible to any clients with a TagQuery using the corresponding tag. A tag is a number of strings comma-delimited or delimited using "|". Eg.: "red|blue" will match with a TagQuery using a tag of "red" or "blue" or both.

Preserve Children

When enabled, networked entities parented to this entity are not destroyed when this entity is destroyed.

They will be automatically unparented before the entity is destroyed instead.

When Preserve Children is enabled CoherenceSync.SetActive(false) should be used instead of GameObject.SetActive(false). This helps avoid the error Cannot set the parent of the GameObject 'X' while activating or deactivating the parent GameObject 'Y'.

Floating Origin Mode

Specifies what should happen to the entity when it is a root GameObject in a scene hierarchy and CoherenceBridge.TranslateFloatingOrigin is executed.

Move With Floating Origin

When you change your floating origin, the Entity is moved with it, so its relative position is the same and absolute position is shifted.

Don't Move With Floating Origin

When you change your floating origin, the Entity is left behind, so its absolute position is the same and relative position is shifted.

Floating Origin Parented Mode

Specifies what should happen to the entity when it is a child GameObject and CoherenceBridge.TranslateFloatingOrigin is executed.

Move With Floating Origin

When you change your floating origin, the Entity is moved with it, so its relative position is the same and absolute position is shifted.

Don't Move With Floating Origin

When you change your floating origin, the Entity is left behind, so its absolute position is the same and relative position is shifted.

Synchronization Channel

Specifies the channel over which this entity will be synchronized (creation, destruction, binding synchronization).

Default

Default reliable channel that guarantees eventual consistency, but does not guarantee receive order.

Fragmented

Reliable channel that guarantees eventual consistency, but does not guarantee receive order.

Can handles data of any size by splitting it into fragments.

This option should not be used for data requiring low latency.

CoherenceSync Events

You can hook into the events fired by the CoherenceSync to conveniently structure gameplay in response to key moment of the component's lifecycle. Events are initially hidden, but you can reveal them using the button at the bonttom of the Inspector called "Subscribe to...".

The list of available CoherenceSync events

Once revealed, you can use them just like regular UnityEvents:

The OnStateAuthority event revealed

You can also subscribe to these events in code.

You might also want to check out the CoherenceSync instance lifecycle section at the bottom of the Order of execution article.

Fix Invalid Bindings

Invalid bindings error is something that happens very often when you have a [Sync] attribute on a field, or a [Command] attribute on a method, and you make some modifications in code to those members, for example adding a new parameter to a method.

coherence has a built-in option to fix invalid bindings for just such cases. The Remove All Invalid Bindings button appears in the CoherenceSync Inspector view:

coherence detects the presence of invalid bindings automatically and lets you know if they appear.

Clicking this button removes broken bindings within the selected CoherenceSync Object that contains invalid data, such as:

  • Bindings pointing a field or method that has been removed.

  • Bindings pointing a field or method that has been renamed.

  • Bindings targeting a component that has been removed from the game object.

  • Binding targeting an animator parameter that has been renamed or removed.

  • Duplicate bindings.

Last updated

Was this helpful?