Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
In this section, we will learn how to prepare a Prefab for network replication.
Setting up basic syncing is explained in this video, from 1:00 and onwards:
You can let the coherence Hub guide you through your Prefab setup process. Simply select a Prefab, open the GameObject tab in the coherence Hub (coherence > coherence Hub) and follow the instructions.
You can also follow the detailed step-by-step text guide below.
CoherenceSync
to your GameObjectFor a Unity GameObject to be networked through coherence, it needs to have a CoherenceSync
component attached. Currently, only Prefabs are supported. If your GameObject is not a Prefab, CoherenceSync
can assist you.
First, create a new GameObject. In this example, we're going to create a Cube.
Next, let's add the CoherenceSync
component to this Cube.
The CoherenceSync
inspector now tells us that we need to make a Prefab out of this GameObject for it to work. We get to choose where to create it.
In this example, we'll be creating it in 📁 Assets / Resources
by clicking Convert to Prefab in Resources.
If you wish to start networking a Prefab that already exists in your project, you have more options to get started:
Clicking on the Sync with coherence checkbox at the top of the Prefab inspector.
Manually adding the CoherenceSync component.
Drag the Prefab to the CoherenceSync Objects Window you can find in coherence > CoherenceSync Objects.
One way to configure your Prefab, instead of just adding CoherenceSync
into it, is to fork a Prefab variant and add the component there.
In our Cube example, instead of adding the component to the original Prefab, you can create a variant called Cube (Networked) and add CoherenceSync
to it:
Learn how to create and use Prefab variants in the Unity Manual.
This way, you can retain the original Prefab untouched.
Another way to use Prefab variants to our advantage is to have a base Prefab using CoherenceSync
, and create Prefab variants off that one with customizations. For example, Enemy (base Prefab) and Enemy 1, Enemy 2, Enemy 3... (variant Prefabs, using different models, animations, materials, etc.). In this setup, all of the enemies will share the networking settings stored in CoherenceSync
, so you don't have to manually update every one of them.
When the Prefab variant inherits the network settings from the Prefab parent, you can configure your Prefab variant with overrides in the Configuration window. When a synced variable, method or component action is present in the variant and not in the parent, it will be bolded and it will have the blue prefix beside it, just like any other override in Unity.
The CoherenceSync
component will help you prepare an object for network synchronization during design time. It also exposes an API that allows us to manipulate the object during runtime.
CoherenceSync
scans all public variables and methods on any of the attached components, for example Unity components such as Transform
, Animator
, etc. This will include any custom scripts and even scripts that came with the Asset Store packages that you may have downloaded.
You can find out more about all of CoherenceSync
properties here.
Select which properties you would like to sync across the network. Initially, this will probably be the Transform
properties: position, rotation, scale.
Click the Configure button in the CoherenceSync
Inspector. A new window will open, called Configuration.
Click on the tab Variables. Since position is already selected, add rotation and localScale.
Close the Configuration window.
Tip: You can also configure variables, methods and components on child objects in the CoherenceSync hierarchy. To do that, simply select the desired object in the Hierarchy window, and the Configuration window will show information for that specific object — similarly to how the Inspector works.
This simple input script will use WASD or the Arrow keys to move the Prefab around the scene.
Click on Assets > Create > C# Script.
Name it Move.cs
. Copy-paste the following content into the file.
Wait for Unity to compile the file, then add it onto the Prefab.
We have added a Move
script to the Prefab. This means that if we just run the scene, we will be able to use the keyboard to move the object around.
But what happens on other Clients where this object is not authoritative, but replicated? We will want the position to be replicated over the network, without the keyboard input interfering with it.
Under Configure, click Components.
Here you will see a list of Component Actions that you can apply to non-authoritative GameObjects that have been spawned by the network.
Selecting Disable for your Move
script will make sure the Component is disabled for network instances of your Prefab.
By extending the ComponentAction
abstract class, you can implement your own Component Actions.
Your custom Component Action must implement the following methods:
OnAuthority
This method will be called when the object is spawned and you have authority over it.
OnRemote
This method will be called when a remote object is spawned and you do not have authority over it.
It will also require the ComponentAction
class attribute, specifying the type of Component that you want the Action to work with, and the display name.
For example, here is the implementation of the Component Action that we use to disable Components on remote objects:
From the CoherenceSync
component you can configure settings for Lifetime (Session-based
or Persistent
, Authority transfer (Request
or Steal
), Simulation model (Client Side
, Server Side
or Server Side with Client Input
) and Adoption settings for when local persistent entities are orphaned.
There are also some Events that are triggered at different times.
On Before Networked Instantiation
(before the GameObject is instantiated)
On Networked Instantiation
(when the GameObject is instantiated)
On Networked Destruction
(when the GameObject is destroyed)
On Authority Gained
(when authority over the GameObject is transferred to the local client)
On Authority Lost
(when authority over the GameObject is transferred to another client)
On After Authority Transfer Rejected
(when GameObject's Authority transfer was requested and denied).
On Input Simulator Connected
(when client with simulator is ready for Server-side with Client Input)
On Input Owner Assigned
(when InputOwner was changed is ready)
CoherenceSync
componentsIt is possible to nest network entities into each other both at edit and at runtime. Doing it at runtime is semi-automatic, and only if you nest an entity deeply into a hierarchy (like a tool in the hands of a character), you need to add the CoherenceNode
component to the nested one.
For edit-time nesting instead, the PrefabSyncGroup
needs to be placed on the root object.
Helper scripts and samples can be found here. These cover things such as:
Spawning a player
Basic inputs to get Game Objects moving
Score keeper
Displaying player names
Camera facing UI
Off-screen spawning of enemies or other Game Objects
Indicator (arrow) for guiding the player towards off-screen Game Objects
Implementing Network Commands and Authority Transfer
Connection Events
Now we can build the project and try out network replication locally.
This example will show you how to launch a local Replication Server and connect multiple instances.
You can run a local Replication Server from the coherence menu:
This will open a new terminal window with the Replication Server and a World created in it.
As with most features found in the menu, you can find local replication server functionality in the Coherence Hub as well. Open the Servers tab and run a Room or a World Replication Server.
Now it's time to make a standalone build and test network replication.
#protip: Go to Project Settings, Player and change the Fullscreen Mode to Windowed and enable Resizable Window. This will make it much easier to observe standalone builds side-by-side when testing networking.
Open the Build Settings window (File > Build Settings). Click on Add Open Scenes to add the current scene to the build. Click Build and Run.
Select a folder (e.g. Builds) and click OK.
When the build is done, start another instance of the executable (or run the project in the Game Window in Unity).
Click Connect on both clients. Now try focusing one and using WASD keys. You will see the box move on the other side as well.
Congratulations, you've made your first coherence replicated experience. But this is only the beginning. Keep reading to take advantage of more advanced coherence features.
coherence currently supports Unity. For custom engine integration, please contact our developer relations team. For updates regarding Unreal Engine support, please check the Unreal Engine support page.
Latest Unity 2021 LTS and 2022 LTS are officially supported. Check LTS Releases.
The minimum supported version is now Unity 2021.3 LTS.
First, go to Edit > Project Settings. Under Package Manager, add a new Scoped Registry with the following information:
Name: coherence
URL: https://registry.npmjs.org
Scope(s): io.coherence.sdk
Now open Window > Package Manager. Select My Registries in the Packages dropdown.
Highlight the coherence package, and click Install.
Refer to Unity's instructions on modifying your project manifest.
Edit <project-path>/Packages/manifest.json
.
Add an entry for the coherence sdk on the dependencies
object, and for the scoped registry in the scopedRegistries
array:
You will then see the package in the Package Manager under My Registries.
When you successfully install the coherence SDK the Welcome Window will show.
Now we can finally deploy our schema and Replication Server on coherence Cloud.
In this example we're working with Worlds. Make sure you have created a World before trying to deploy the Replication Server. To create a World, follow the steps described in Manage Worlds.
The topics on this page start from around 1:00 in the video below:
In the coherence Hub window, select the coherence Cloud tab, and click on Upload to coherence Cloud in the Schemas section.
The status in the Schemas section should now be In Sync.
If the status does not say "In Sync", or if you encounter any other issues with the server interface, refer to the troubleshooting section.
Your project schema is now deployed with the correct version of the Replication Server already running in the cloud. You will be able to see this in your cloud dashboard status.
The Connect Dialog fetches all the regions available for your project. This depends on the project configuration (e.g., the regions that you have selected for your project in the Portal).
You can now build the project again and send the build to your friends for testing.
You will be able to play over the internet without worrying about firewalls and local network connections.
Before connecting, make sure everybody selects the same region, and that this region is not local.
For quick and easy testing, we suggest trying out the publish to WebGL option. Anyone with the link can then try the build in a browser.
Keep in mind to add the description of game controls though!
The coherence package comes with several samples you can choose to add to your project. Each provides Prefabs and scripts that you can add to your Scene and edit however you want.
There are currently 3 samples available: a Room connection dialog, a World connection dialog, and Lobby connection dialog.
The difference between Rooms and Worlds is explained on this page: Rooms and Worlds. You can also read more about Lobbies.
Each sample comes with a Prefab that can be added to the Scene. You can add them through coherence > Explore Samples.
Effectively these do two things for you :
Import the sample in the Samples directory of your project, if it isn't already.
Add the Prefab from the sample to your Scene.
From the example above, that would be Room Connection Dialog.prefab
.
The Rooms Connect Dialog has a few helpful components that are explained below.
At the top of the dialog we have an input field for the player's name.
Next is a toggle between Cloud and Local. You can switch to Local if you want to connect to a Rooms Server that is running on your computer.
Next is a dropdown for region selection. This dropdown is populated when regions are fetched from the coherence cloud. The default selection is the first available region. This is not enabled when you switch from Cloud to Local. This is also only relevant if you deploy your game to several different regions.
Next is a dropdown of available Rooms in the selected region (or in your local server if using the Local mode).
After selecting a Room from the list the Join button can be used to join that Room.
If you know someone has created a room but you don't see it, you can manually refresh the rooms list using the Refresh button.
The Create a room section adds a Room to the selected region.
This section contains controls for setting a Room's name and maximum player capacity. Pressing the Create button will create a Room with the specified parameters and immediately add it to the Room Dropdown above. Create and Join will create the Room, and also join it immediately.
The Worlds Connect Dialog is much simpler. It simply holds a dropdown for region selection, an input field for the players name, and a Connect button.
If you start a local World server, it will appear as LocalWorld
.
Samples are copied to your project, this means you can change and customize the scripts and Prefabs however you like.
Future versions of coherence won't override your changes. If you upgrade to a newer version of coherence and import a new sample, they will be imported in a separate folder named after the coherence version.
If you notice that the samples are non-responsive to input, make sure you have an EventSystem component in the scene.
Quicker iteration during development
When developing multiplayer experiences you will need to run multiple instances of your game in order to test properly. You also need to make sure these instances can be restarted quickly, so you can iterate quickly.
coherence does not have a built-in solution for multiclient testing, but there are several options available to you, each with their own benefits and drawbacks.
ParrelSync is an open-source project which allows you to have multiple Editors open which share Assets and ProjectSettings using Symbolic links.
Benefits
Short iteration times.
Easily debuggable instances.
Drawbacks
Requires you to have multiple Editors open.
Caveats
All instances of the game must have identical schemas, which are NOT shared using ParrelSync. That means you need to bake on all open Editors. Setting Auto Bake on Enter Play Mode to true in coherence Settings will alleviate this issue.
EditorPrefs are not consistently shared between Editors.
First, install the ParrelSync package as described in the Installation Instructions.
Open ParrelSync -> Clones Manager. Create a new clone, and open it.
Continue development in the original Editor.
When you need to test, do the following for all open Editors: Bake, press play. Alternatively you can set Auto Bake on Enter Play Mode to true.
The easiest method is to simply create a new build each time you want to test anything. You can launch any number of instances of that build, and have an instance running in the Editor as well.
Benefits
Easy to distribute amongst team members.
Well-understood workflow.
Drawbacks
Long iteration time as you need to continuously make builds.
Harder to debug the executables.
Caveats
All instances of the game must have identical schemas, so remember to bake before building the executable.
Unity has an experimental package called Multiplayer Play Mode (MPPM) available for 2023.1. As this is currently experimental, we do not officially recommend it - but it does show some promise and should be mentioned. This package allows a single Editor to run several instances of a game.
Benefits
Short iteration times.
No issues with schema incompatibility.
Drawbacks
Experimental.
Now that we have tested our project locally, it's time to upload it to the cloud and share it with our friends and colleagues. To be able to do that, we need to create a free account with coherence.
In your web browser, navigate to https://coherence.io/dev.
Create an account or log into an existing one.
Open Unity and open the coherence Hub window. Then open the coherence Cloud tab.
After pressing Login you will be taken to the login page. Simply login as usual, and return to Unity.
You are now logged into the Portal through Unity. Select the correct Organization and Project, and you are ready to start creating.
coherence allows you to upload and share the builds of your games to your team, friends or adoring fans via an easy access play link.
Right now we support desktop (PC, Mac, Linux) and also WebGL, where you can host and instantly play your multiplayer game and share it around the world.
Build your game to a local folder on your desktop as you would normally.
In the coherence Hub window, select the coherence Cloud tab. You can upload your build from the Share Build section of the tab, select the platform (macOS, Linux, Window or WebGL are supported) and click on the Begin Upload button.
Now that build has been updated (signified by the green tick), you can share it by enabling and sharing the public URL. Anyone with this link can access the build.
If you uploaded a WebGL build, the public link allows for instant play.
It's quick and easy to set up a networked scene from scratch using the coherence SDK.
The topics of this page are covered in the first minute of this video:
Preparing a scene for network synchronization requires to add three fundamental objects:
coherence > Scene Setup > Create CoherenceBridge
This object takes care of connected GameObject
lifetimes and allows us to develop using traditional MonoBehaviour
scripts.
coherence > Scene Setup > Create LiveQuery
Creates a LiveQuery which queries the area around the local player to get the required information from the Replication Server. You can surround your entire scene in one query or can attach it to an object such as the player or a camera.
You don't have to define a range for the LiveQuery. Leaving the range to 0 means that the range is infinite, so nothing is filtered out.
coherence > Explore Samples
A Connect dialog UI provides an interface to the player to connect to the Replication Server, once the game is played. You can create your own connection dialog, but we provide a few samples as a quick way to get started.
If you're unsure about which dialog to add, choose Rooms for now. You can read more about Rooms and Worlds.
The connection dialog samples we provide are here for you to completely customize, you can read more in the section dedicated to Samples.
Using the coherence Hub window gives you an overview of everything related to networking in your project. The Overview tab will show you the current status and which actions you need to perform for everything to work.
To open it, go to coherence > coherence Hub