LogoLogo
⚠️ Outdated documentationGo to LatestHomeAPI
SDK 1.1
SDK 1.1
  • Welcome
  • Overview
    • What is coherence?
    • How does coherence work?
    • Rooms and Worlds
    • Features and Roadmap
    • Release Notes
    • Known issues and Troubleshooting
  • Learn
    • Beginner's guide to networking
    • Package samples
    • First Steps tutorial
      • 1. Basic syncing
        • 1.2. Animation parameters
        • 1.3. Sending commands
      • 2. Physics / Authority transfer
      • 3. Areas of interest
      • 4. Parenting entities
      • 5. Complex hierarchies
      • 6. Persistence
    • Campfire project
      • Game mechanics
      • Leveraging object pooling
      • Remote interactions: Chairs
      • Remote interactions: Trees
      • A unique object with complex state
      • Custom instantiation and destruction
      • Running a server-side NPC
      • Playing audio and particles
      • A simple text chat
    • How to network [genre]…
      • Racing
      • Turn-based
      • First-Person Shooter
      • MMO
      • Fighting
    • Video tutorials
  • Get started
    • Installation
    • Scene Setup
      • Sample UIs
    • Prefab setup: CoherenceSync
    • Testing locally
      • Tips and recommendations
    • coherence Cloud
      • Create a free account
      • Deploy a Replication Server
      • Share builds
  • coherence SDK for Unity
    • Components
      • CoherenceSync
      • CoherenceBridge
      • CoherenceLiveQuery
      • CoherenceTagQuery
      • Order of execution
    • Asset Management
      • Using CoherenceSyncConfig to instantiate GameObjects locally
      • CoherenceSyncConfigRegistry Save Modes
    • Networking State Changes
      • Supported types
      • Messaging with Commands
      • Syncing child GameObjects
      • Parenting network entities
        • Direct child CoherenceSyncs
        • Deeply-nested CoherenceSyncs
        • Nesting Prefabs at Edit time
      • Animation
      • CoherenceSync references
      • [Sync] and [Command] Attributes
      • [OnValueSynced] Attribute
      • Creating your own syncable member
      • Custom Component Actions
    • Baking (Code generation)
    • Scene Management
    • Authority
      • Authority transfer
      • Server-authoritative setup
    • Lifetime
      • Persistence
      • Example – a global counter
    • Optimization
      • Simulation Frequency
      • Areas of Interest
      • Level of Detail (LOD)
    • Profiling
    • Interpolation
    • Rigid Bodies
    • Settings
    • Simulation Frame
    • Replication Server
    • Simulators
      • Scripting: Client vs Simulator
      • Local Development
      • World Simulators
      • Room Simulators
      • Simulator Slugs
      • Multi-Room Simulators
      • Build and Publish
      • Command-line arguments
      • Load Balancing
    • Client-Hosting
    • Client Connections
    • Rollback Networking Support
    • World Origin Shifting
    • Offline gameplay
    • CLI
    • Upgrade Guide
      • Upgrade 1.0 -> 1.1
      • Upgrade 0.10 -> 1.0
      • Upgrade 0.9 -> 0.10
  • Hosting
  • coherence Cloud
    • Developer Portal
    • Dashboard
    • Worlds
    • Rooms
    • Lobbies
    • Game Services
      • Account
      • Key-Value Store
    • Using coherence Cloud in Unity
      • Worlds
      • Rooms
      • Lobbies
      • Game Services
        • Authentication Service (Player Accounts)
        • Key-value store
  • Schema explained
    • Overview
    • Specification
    • Field settings
    • Archetypes
  • coherence Scripting API
  • Additional resources
    • Community
    • Pricing
    • Quick Samples
    • Continuous Integration
    • Unreal Engine Support
    • WebGL Support
    • Peer-to-Peer Support (P2P)
    • Glossary
  • Credit cost & pricing
Powered by GitBook
On this page
  • Video tutorial
  • Using the coherence Hub
  • Step by step
  • 1. Add CoherenceSync to your GameObject
  • (Optional) Networking an already existing Prefab
  • (Optional) Prefab variants
  • 2. Configure CoherenceSync
  • 2.1 Select variables to replicate
  • 3. Add a movement script
  • 4. Disable the component on replicated objects
  • 5. Bake the netcode
  • To recap
  • Helper scripts

Was this helpful?

Export as PDF
  1. Get started

Prefab setup: CoherenceSync

Last updated 1 year ago

Was this helpful?

In this section, we will learn how to prepare a Prefab for network replication.

Video tutorial

Setting up basic syncing is explained in this video, from 1:00 and onwards:

Using the coherence Hub

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.

Step by step

You can also follow the detailed step-by-step text guide below.

1. Add CoherenceSync to your GameObject

For 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, we add the CoherenceSync component to Cube.

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:

(Optional) Networking an already existing Prefab

If you wish to start networking a Prefab that already exists in your project, you have several options to do it. Remember that they all lead to the same result.

You can:

  • Click on the Sync with coherence checkbox at the top of the Prefab inspector.

  • Manually add the CoherenceSync component.

  • Drag the Prefab to the CoherenceSync Objects window. You can find it in coherence > CoherenceSync Objects.

(Optional) Prefab variants

One way to configure your Prefab instead of just adding CoherenceSync to it, is to fork a Prefab variant and add the component there.

In our Cube example, instead of adding CoherenceSync to Cube, you can create a Cube (Networked) Prefab and add CoherenceSync to it:

This way, you can retain the original Prefab untouched, and build all the network functionality separately, in its own Prefab.

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.

The Prefab variant inherits the network settings from its parent, and you change those 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 line next to it, just like any other override in Unity:

2. Configure CoherenceSync

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.

In its Inspector you can configure settings for Lifetime (Session-based or Persistent), Authority transfer (Not Transferable, Request or Steal), Simulate In (Client Side, Server Side or Server Side with Client Input) and Adoption settings for when persistent entities become orphaned, and more.

There are also a host of Events that are triggered at different times.

For now, we can leave these settings to their defaults.

2.1 Select variables to replicate

CoherenceSync allows you to automatically network all public variables and methods on any of the attached components, from Unity components such as Transform, Animator , etc. to any custom script, including scripts that came with the Asset Store packages that you may have downloaded.

To set it up, click on the Configure button in the CoherenceSync's Inspector. This brings up the Configuration window. Here you can select which variables you would like to sync across the network:

You will notice that position is already selected, and can't be removed. For our use case, let's add rotation and scale.

Close the Configuration dialog.

3. Add a movement script

This simple movement 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:

Move.cs
using UnityEngine;

public class Move : MonoBehaviour
{
    public float speed = 1f;

    void Update()
    {
        float h = Input.GetAxisRaw("Horizontal");
        float v = Input.GetAxisRaw("Vertical");
    
        var spf = speed * Time.deltaTime;

        transform.position += transform.forward * (v * spf);
        transform.position += transform.right * (h * spf);
    }
}

Wait for Unity to compile the file, then add it to the Prefab.

4. Disable the component on replicated objects

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 want the position to be replicated over the network without keyboard input interfering with it.

In the Configuration window, click the Components tab:

Here you will see a list of Component Actions that you can apply to non-authoritative entities 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:

This ensures that, if a copy of this Prefab is instantiated on a Client with no authority, this script will be disabled and won't interfere with the position that is being synced on the network.

5. Bake the netcode

This process is very quick, and can be done in different ways:

  • From the menu item coherence > Bake

  • Within the coherence Hub, in the Baking tab, using Bake Now:

  • When a Prefab contains changes that need baking, its Inspector will warn you. Pressing Bake here will actually bake all code for all Prefabs:

To recap

In short, setting up a Prefab for networking requires:

  • A Prefab with a CoherenceSync added to it

    • Optionally, setting some of its properties

  • Configuring what to sync in the Configure window

  • Disabling components on remote entities, in the Configure > Components tab

  • Baking the netcode

This is it! Setting up a Prefab to be networked doesn't require additional steps.

Helper scripts

  • 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

Learn how to create and use Prefab variants in the .

Its Inspector has quite a number of settings. For more information on them, refer to .

Note that you can configure variables, methods and components not only on the root, but also .

Once everything is setup, you should ensure to run the process of : coherence will produce the necessary netcode (i.e. a bunch of C# scripts) to ensure that when the game is running and the Client connects, all of the properties and network messages you might have configured will correctly sync.

Now you can run this setup or using the .

Helper scripts and samples can be found . These cover things such as:

Unity Manual
the CoherenceSync page
on child GameObjects
Baking
locally
coherence Cloud
here
Networking an existing Prefab
Creating a variant of Cube
Prefab variant with a few overriden synced properties
CoherenceSync inspector
Configure Window
If the Bake Now button has a warning, you need to bake before running the game