Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Refer to the Level of detail section for more information.
CoherenceSync is a component that should be attached to every networked Game Object. 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. You can select which of the attached components you would like to sync across the network as well as individual public properties.
All Networked Entities need to be placed in the Resources folder
Any scripts attached to the component with CoherenceSync that have public variables will be shown here and can be synced across the network. Enable the script + the variable to sync, it's that easy. Those variables with a lightning bolt next to them signify a public method that can be activated via commands.
Ownership Transfer
When you create a networked game object, you automatically become the owner of that game object. That means only you are allowed to update or destroy it. But sometimes it is necessary to pass ownership from one player to another. For example, you could snatch the football in a soccer game or throw a mind control spell in a strategy game. In this case, you will need to transfer ownership from one client to another.
Entity Lifetime
When a player disconnects, all the game objects created by that player are usually destroyed. If you want any game objects to stay in the game world after the owner disconnects, you need to set Entity lifetime type of that game object to Persistent.
Session Based - Will be removed when the client disconnects
Persistence - Entities with this option will persist as long as the server is running. Auto Generate Persistance UUID
should be checked so that a unique identification string will be used to regenerate the object when you reconnect to the server. When the entity is spawned with this checked it will generate its own UUID.
Uniqueness
Allow Duplicates - no restrictions on which objects can be instantiated over the network.
No Duplicates - ensure objects are no duplicated by marking them with a UUID. You can provide your own, left the field blank (a GUID will be assigned at runtime), or use the CoherenceUUID component helper to generate GUIDs for you at editor time.
Entity Simulation Type
Client Side - Simulates everything on the local client and passes the information to the Replication Server to distribute that information to the other clients.
Other forms of simulation (Server; Server with Client Input) coming soon.
Authority Transfer Style
Not Transferable - The default value is Not Transferable because most often objects are not meant to be transferred.
Stealing - Allows the game object to be transferred to another client.
Request - This option is intended for conditional transfers, which is not yet supported.
Orphaned Entities
By making the game object persistent, you ensure that it remains in the game world even after its owner disconnects. But once the game object 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 game object.
In order to make the orphaned game object interactive again, another client needs to take ownership of it. To do this, enable Auto-adopt orphan
.
Once you have set the transfer style to stealing, any client can request ownership by calling the RequestAuthority()
method on the CoherenceSync component of that game object:
someGameObject.GetComponent<CoherenceSync>().RequestAuthority();
A request will be sent to the game object's current owner. The current owner will then accept the request and complete the transfer.
You are now the new owner of the game object. This means the isSimulated
flag has been set to true, indicating that you are now in full control of the game object. The previous owner is no longer allowed to update or destroy it.
Helper scripts with a custom implementation of Authority transfer can be found here.
Events for handling user connection and disconnection. Manual Destory
is useful for session based objects that you want to keep "semi persistent" which would be removed when all the clients disconnect.
When CoherenceSync variables/components sent over the network, by default, reflection is used to sync all the data at runtime. Whilst this is really useful for prototyping quickly and getting things working, it can be quite slow and unperformant. A way to combat this is to bake the CoherenceSync component, generating a compatible schema and generating code for it.
The schema is a file that defines which data types in your project are synced over the network. It is the source from which coherence SDK generates C# struct types (and helper functions) that are used by the rest of your game. The coherence Replication Server also reads the Schema file so that it knows about those types and communicates them with all of its clients efficiently.
The schema must be baked in the coherence Settings window before the check box to bake this prefab can be clicked.
When the CoherenceSync component is baked, it generates a new file in the baked folder called CoherenceSync<NameOfThePrefab>
. This component will be instantiated at runtime, and will take care of networked serialization and deserialization, instead of the built-in reflection-based one.
Refer to the commands section.
The coherence Sample UI
is a prefab that you can add to your scene that handles interaction with coherence services. It is made up of a Unity UI Canvas and includes everything needed to handle connection to coherence.
The Connect Dialog Selector
component on the root of the prefab allows us to switch between using Rooms
or Worlds
each of these methods has a dedicated dialog for connection.
The Auto Reconnect
components are used by Simulator builds. The relevant Auto Reconnect
component is also enabled when switching between Rooms and Worlds.
To learn more about simulators see Simulators
The Rooms Connect Dialog
has a few components that facilitate usage of Rooms.
At the top of the dialog is a dropdown for region selection. This dropdown is populated when regions are fetched and automatically selects the first one available.
Due to current limitations the local server is fetched only if it's started before you enter play mode. The Allow local
checkbox must also be checked.
This effects the local region for Rooms and the local worlds for Worlds.
Next the dialog holds an input field for the players name.
Beneath these elements is a tab group with two sections.
The first section holds a list of rooms fetched from the currently selected region. The user can select one of these rooms and connect to it using the join button. On the left of this tab is a button to refresh the rooms list, fetching them again. This refresh is also triggered whenever the selected region is changed.
The second section is used for room creation. Two input fields allow us to specify a room name and a maximal number of players.
The buttons at the bottom of this section then allow the creation of a room with the specified parameters. The Create and Join
button allows the user to automatically connect to the room that was created by the request right away.
The Worlds Connect Dialog
is much simpler. It holds a dropdown for world selection, an input field for the players name, and a connect button.
The dropdown is populated when worlds are fetched and automatically selects the first one available.
The connect button tells the client to connect to the selected world.
Note: You can also build your own interface to connect players to the server using thePlayResolver
API to learn more about the API see PlayResolver, Rooms or Worlds according to what your project needs.
The way you get information about the world is through LiveQueries. We set criteria for what part of the world we are interested in at each given moment. That way, the replicator won’t send information about everything that is going on in the game world everywhere, at all times.
Instead, we will just get information about what’s within a certain area, kind of like moving a torch around to look in a dark cave.
More complex areas of interest types are coming in future versions of coherence.
A LiveQuery is a cube that defines the area of interest in a particular part of the world. It is defined by its position and its radius (half the side of the cube). There can be multiple LiveQueries in a single scene.
A classic approach is to put a LiveQuery on the camera and set the radius to correspond to the far clipping plane or visibility distance.
Moving the GameObject containing the LiveQuery will also notify the replication server that the query for that particular game client has moved.
The coherence Settings window is located in Project Settings -> coherence
and lets you launch a local replication server, upload your server to the cloud via the access token and bakes your Schemas for more optimized data transfer of Networked GameObjects.
Bake Schemas
When CoherenceSync variables/components are sent over the network, C# reflection is used to sync all the data at runtime. Whilst this is really useful for prototyping quickly and getting things working, it can be quite slow and poorly performing. A way to combat this is to bake the CoherenceSync component into a Schema.
The Schema is a text file that defines which data types in your project are synced over the network. It is the source from which coherence SDK generates C# struct types (and helper functions) that are used by the rest of your game. The coherence Replication Server also reads the Schema file to know about those types and to communicate them with all of its clients efficiently.
The Schema must be baked in the coherence Settings window, before the check box to bake this prefab can be clicked.
When the CoherenceSync component is baked, it generates CoherenceSync<NameOfPrefab>.cs
.
Bake Output Folder
Defines where to store the baked Schema files.
Portal
Upload your Schema files to your server.
Status - Current Status of your cloud server
Token - Cloud token
Local Replication Server
Run a local replication server.
Port - The port access
Frequency - Frequency of server.
Rooms functionality can be accessed through the PlayResolver
which includes all the methods needed to use rooms.
To manage rooms we must first decide which region we are working with.
FetchRegions
in PlayResolver.cs
allows us to fetch the regions available for our project. This task returns a list of regions (as strings) and a boolean that indicates if the operation was successful.
FetchLocalRegions
in PlayResolver.cs
returns the local region string for a local running rooms server, or null if the operation is un-successful (if the server isn't running for example).
Every other rooms API will require a region string that indicates the relevant region for the operation so these strings should not be changed before using them for other operations.
The RoomsConnectDialog
populates a dropdown with the region strings returned by both of these methods directly for easy selection.
These methods also call EnsurePlayConnection
which initializes the needed mechanisms in the PlayResolver
if necessary. EnsurePlayConnection
can also be called directly for initialization.
After we have the available regions we can start managing rooms, for instance:
CreateRoom
in PlayResolver.cs
allows us to create a room in the region we send it.
We can also optionally specify:
a room name
the maximal number of clients allowed for the room
a list of tags for room filtering and other uses
a key-value collection for the room
This task returns the operations result and RoomData
for the created room assuming the operation was successful.
FetchRooms
in PlayResolver.cs
allows us to search for available rooms in a region. We can also optionally specify tags for filtering the rooms.
This task returns a list of RoomData
objects for the rooms available for our specifications.
JoinRoom
in PlayResolver.cs
connects the client that we pass to the method to the room we pass to the method. This RoomData
object can be either the one we get back from CreateRoom
or one of the ones we got from FetchRooms
.
The RoomsConnectDialog
demonstrates both of these cases in CreateRoom
when called with true for autoJoin and in JoinRoom
respectively.
The coherence SDK is a set of prefabs & scripts to help you create multiplayer games super fast.
It makes it easy for anyone to create a multiplayer game by having flexible, intuitive and powerful visual components.
Here are the main building blocks of the SDK.
CoherenceSync is a component that should be attached to every networked Game Object. 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. You can select which of the attached components you would like to sync across the network as well as individual public properties.
The coherence Settings window is located in Project Settings -> coherence
and lets you launch a local replication server, upload your server to the cloud via the access token and bakes your schemas for more optimized data transfer of our Networked GameObjects.
LiveQuery, as the name suggests, queries a location set by the developer so that coherence can simulate anything within its radius. In our Starter Project, the LiveQuery position is static with a radius large enough to cover the entire playable level. If the world was very large and potentially set over multiple simulation servers, the LiveQuery could be attached to the playable character or camera.
The coherence MonoBridge passes information between the coherenceSync component and the networked ECS components.
The sample UI Prefab holds all of the UI and connection functionality to connect to the running project locally or via a server. You can completely rewrite this if you like, it's there to get you up and running quickly.
The built-in coherence scripts are configured to execute in a specific order, using the following DefaultExecutionOrder
setup:
-1000 CoherenceMonoBridge
-900 CoherenceSync
-800 CoherenceInput
1000 CoherenceMonoBridgeSender
This is an advanced topic that aims to bring access to coherence's internals to the end user.
CustomBindingProviders are editor classes that tell coherence how a specific component should expose its bindings and how it generates baked scripts.
For example, we could create a custom binding provider for our Health component:
Place CustomBindingProviders inside an Editor folder.
We can add additional (custom) bindings:
In order for these new custom bindings to work on reflected mode, we'll need to implement a runtime serializer that understands how to deal with them.
Check the CustomBinding.Descriptor
API for further properties, like interpolation or marking the binding as required.
For custom bindings to work on reflected mode, we need to implement how their values are serialized and deserialized at runtime:
CustomBindingRuntimeSerializers should be placed in a non-Editor folder.
Once we have our runtime serializer, we need to make our binding provider use it:
You can extend an already existing CustomBindingProvider. For example, coherence ships with a CustomBindingProvider for Transforms:
This way, you can define additional rules on how you want to treat your Transforms, for example.
Any amount of CustomBindingProviders can be registered over the same component, but only one being used. The one being used, is resolved by a priority integer that you can specify in the CustomBindingProvider attribute. The class with the higher priority defined in the attribute will be the only provider taken into account:
The default priority is set at 0
, and coherence's internal CustomBindingProviders have a priority of -1
.
To understand how these APIs are used, check out TransformBindingProvider and AnimatorBindingProvider, both shipped with the coherence SDK (<package>/Coherence.Editor/Toolkit/CustomBindingProviders
).
The MonoBridge is a system that makes sure every GameObject is linked to its networked representation. It essentially interfaces between the GameObject world and the coherence SDK code running "under the hood".
When you place a GameObject in your scene, the MonoBridge detects it and makes sure all the synchronization can be done via the CoherenceSync component.
Worlds functionality can also be accessed through the PlayResolver
just like rooms. Worlds work a differently however and are a bit simpler.
First we need to fetch the available worlds. Unlike rooms, worlds cannot be created by a client and need to be setup in the developer portal.
FetchWorlds
in PlayResolver.cs
allows us to fetch the available worlds for our project. This task returns a list of worlds in the form of WorldsData
objects and a boolean that indicates if the operation was successful.
This method also call EnsurePlayConnection
which initializes the needed mechanisms in thePlayResolver
if necessary. EnsurePlayConnection
can also be called directly for initialization.
FetchLocalWorld
in PlayResolver.cs
returns the local world for a local running world server.
The WorldsConnectDialog
populates a dropdown with the worlds returned by both of these methods so we can select a world.
After we've selected a world we can connect to it using:
JoinWorld
in PlayResolver.cs
connects the client that we pass to the method to the world we pass to the method.
The isSimulator
optional parameter is used for simulators and can be ignored for regular client connections (see Simulators).
The WorldsConnectDialog
is an example implementation for Worlds usage.