LogoLogo
⚠️ Outdated documentationGo to LatestHomeAPI
SDK 0.10
SDK 0.10
  • Welcome
  • Overview
    • What is coherence?
    • How does coherence work?
    • Rooms and Worlds
    • Features and Roadmap
    • Release Notes
    • Known Issues and Troubleshooting
  • Learning coherence
    • 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
    • How to network...
      • Racing
      • Turn-based
      • First-Person Shooter
      • MMO
      • Fighting
  • Get started
    • Installation
    • Scene Setup
      • Sample UI
    • Prefab Setup: CoherenceSync
    • Local Development
      • Tips and Recommendations
    • coherence Cloud
      • Create a Free Account
      • Deploy a Replication Server
      • Share Builds
  • coherence SDK for Unity
    • Components
      • CoherenceSync
      • CoherenceMonoBridge
      • CoherenceLiveQuery
      • CoherenceTagQuery
      • Order of execution
    • Networking State Changes
      • Messaging with Commands
      • Hierarchies & Child Objects
        • Child GameObjects
        • Child CoherenceSyncs
        • Deep Child CoherenceSyncs
      • Animations
      • CoherenceSync References
      • [Sync] and [Command] Attributes
      • [OnValueSynced] Attribute
      • Supported Types
      • Player Name (Sample UI)
    • Baking (Code Generation)
    • Authority
      • Authority transfer
      • Server-authoritative setup
    • Lifetime
      • Persistence
      • Example – a global counter
    • Optimization
      • Simulation Frequency
      • Areas of Interest
      • Level of Detail (LOD)
    • Interpolation
    • 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
      • Network Connectivity
    • Client Connections
    • Rollback Networking Support
    • Floating Origin
    • CLI
  • coherence API
    • Worlds
    • Rooms
    • PlayResolver
    • DescriptorProvider
  • Developer Portal
    • Overview
    • Dashboard
    • Worlds
    • Rooms
    • Game Services
      • Account
      • Key-Value Store
      • API
        • Game account
        • Key-value store
  • Schema explained
    • Overview
    • Specification
    • Field settings
    • Archetypes
  • Additional resources
    • Community
    • SDK Upgrade Guide
    • Video Tutorials
    • Quick Samples
    • Continuous Integration
    • Unreal Engine Support
    • WebGL Support
    • Peer-to-Peer Support (P2P)
    • Pricing
    • SLA
    • Glossary
Powered by GitBook
On this page
  • Overview
  • Enabling Client Connections
  • Connection Management
  • ClientConnection Objects
  • Client Messages

Was this helpful?

Export as PDF
  1. coherence SDK for Unity

Client Connections

Communication between Clients

Last updated 2 years ago

Was this helpful?

Overview

Client Connections are CoherenceSyncs that the CoherenceMonoBridge can handle for you and let you uniquely identify users connected, find them by their ID, spawn CoherenceSyncs whenever a new user joins the session, and send commands between those users.

When using Client Connections, CoherenceMonoBridge will spawn a CoherenceSync for each connection (Client or Simulator). Those CoherenceSyncs are subject to a different ruleset than standard CoherenceSyncs:

  • They can't be created or destroyed by the Client - they are always driven by CoherenceMonoBridge.

  • They are global - they are replicated across Clients regardless of the extent.

Client Connections shine whenever there's a need to communicate something to all the connected players. Usage examples:

  • Global chat

  • Game state changes: game started, game ended, map changed

  • Server announcements

  • Server-wide leaderboard

  • Server-wide events

Enabling Client Connections

The global nature of Client Connections doesn't fit all game types - for example, it rarely makes sense to keep every Client informed about the presence of all players on the server in an MMORPG. If this is your use case, don't set Client Connections on your CoherenceMonoBridge.

To enable Client Connections, turn Global Query on in your (it should be by default):

Disabling Global Query on one Client doesn't affect other Clients, i.e. the ClientConnection Object of this Client will still be visible to other Clients that have the Global Query turned on.

Connection Management

Most of the Client Connection functionality is accessible through the CoherenceMonoBridge.ClientConnections object:

using System.Collections.Generic;
using Coherence.Connection;
using Coherence.Toolkit;
using UnityEngine;

public class ExampleGameManager : MonoBehaviour
{
    public CoherenceMonoBridge MonoBridge;

    void Start()
    {
        // Raised whenever a new connection is made (including the local one).
        MonoBridge.ClientConnections.OnCreated += connection =>
        {
            Debug.Log($"Connection #{connection.ClientId} " +
                      $"of type {connection.Type} created.");
        };

        // Raised whenever a connection is destroyed.
        MonoBridge.ClientConnections.OnDestroyed += connection =>
        {
            Debug.Log($"Connection #{connection.ClientId} " +
                      $"of type {connection.Type} destroyed.");
        };

        // Raised when all initial connections have been synced.
        MonoBridge.ClientConnections.OnSynced += connectionManager =>
        {
            Debug.Log($"ClientConnections are now ready to be used.");
        };
    }
    
    void Update()
    {
        // IMPORTANT: All of the connection retrieving calls may return null 
        // if the connection system was not turned on, not initialized yet,
        // or simply if the connection was not found.
        
        // Specifies how many clients are in this session (room or world).
        int clientCount = MonoBridge.ClientConnections.ClientConnectionCount;
        
        // Returns connection objects for all connections in this session.
        IEnumerable<CoherenceClientConnection> allConnections
            = MonoBridge.ClientConnections.GetAll();

        // Returns all connections except for the local one.
        IEnumerable<CoherenceClientConnection> otherConnections
            = MonoBridge.ClientConnections.GetOther();

        // Returns connection object of the local user.
        CoherenceClientConnection myConnection
            = MonoBridge.ClientConnections.GetMine();

        // Returns connection object of the simulator (if one is connected).
        CoherenceClientConnection simulatorConnection
            = MonoBridge.ClientConnections.GetSimulator();

        // Retrieves a connection by its ClientID.
        CoherenceClientConnection selectedConnection
            = MonoBridge.ClientConnections.Get(myConnection.ClientId);

        // Retrieves a connection by its EntityID (warning: requires
        // connection prefab with a CoherenceSync attached).
        if (myConnection.Sync != null)
        {
            selectedConnection
                = MonoBridge.ClientConnections.Get(myConnection.Sync.EntityID);
        }

        // Specifies if this is a client or a simulator connection.
        ConnectionType connectionType = selectedConnection.Type;

        // Specifies if this is a local connection (belonging to the
        // local user).
        bool isMine = selectedConnection.IsMyConnection;

        // Returns a GameObject associated with this connection.
        // Applicable only if connection prefabs are used.
        GameObject connectionGameObject = selectedConnection.GameObject;
    }
}

Each connection is represented by a plain C# CoherenceClientConnection object. It contains all the important information about a connection - its ClientID, Type, whether it IsMyConnection, and a reference to the GameObject and Coherence Sync associated with it.

The CoherenceClientConnection.ClientID is guaranteed to not change during a connection's lifetime. However, if a Client disconnects and then connects again to the same Room/World, a new ClientID will be assigned (since a new connection was established).

ClientConnection Objects

Each Client Connection can have a CoherenceSync automatically being spawned and associated with it. Those objects, like any other objects with CoherenceSync, can be used for syncing properties or sending messages, with a little twist - they are global and thus not limited by the LiveQuery extent. That makes them perfect candidates for operations like:

  • Syncing global information - name, stats, tags, etc.

  • Sending global messages - chat, server interaction

To enable connection objects:

1. Create a ClientConnection Prefab

2. Link a ClientConnection Prefab to the CoherenceMonoBridge

For the system to know which object to create for every new Client connection, we have to link our Prefab to the CoherenceMonoBridge. Simply drag the prefab to the Client field in the inspector:

From now on every new connection will be assigned an instance of this Prefab, which can be accessed through the CoherenceClientConnection.GameObject property.

Prefab selection

Note that there's a separate field for the Simulator Connection Prefab. It can be used to spawn a completely different object for the Simulator connection that may contain Simulator-specific commands and replicated properties. If the field is left empty, no object will be created for the Simulator connection.

The Prefab selection process can be also controlled from code using the CoherenceMonoBridge.ClientConnections.ProvidePrefab callback:

using Coherence.Toolkit;
using UnityEngine;

public class ExampleGameManager : MonoBehaviour
{
    public CoherenceMonoBridge MonoBridge;
    public CoherenceSync CustomConnectionPrefab;

    void Start()
    {
        MonoBridge = FindObjectOfType<CoherenceMonoBridge>();
        MonoBridge.ClientConnections.ProvidePrefab += (clientId, connectionType) =>
        {
            return CustomConnectionPrefab;
        };
    }
}

A Prefab provided through the ProvidePrefab callback takes precedence over Prefabs linked in the inspector.

Client Messages

using UnityEngine;

public class PlayerConnection : MonoBehaviour
{
    // My chat command
    public void OnChatMessage(string message)
    {
        Debug.Log($"Received chat message: {message}");
    }
}

Don't forget to bind to the new method to define a command:

Client Messages can be sent using the CoherenceClientConnection.SendClientMessage method:

using UnityEngine;
using Coherence;
using Coherence.Toolkit;

public class PlayerConnection : MonoBehaviour
{
    void Start()
    {
        var monoBridge = FindObjectOfType<CoherenceMonoBridge>();
        CoherenceClientConnection myConnection = monoBridge.ClientConnections.GetMine();

        myConnection.SendClientMessage<PlayerConnection>(nameof(OnChatMessage),
            MessageTarget.Other, "Hello!");
    }

    // My chat command
    public void OnChatMessage(string message)
    {
        Debug.Log($"Received chat message: {message}");
    }
}

If the ClientID of the message recipient is known we can use the CoherenceMonoBridge.ClientConnections directly to send a client message:

private ClientID lastClientId;

private void OnConnectionCreated(CoherenceClientConnection clientConnection)
{
    if (!clientConnection.IsMyConnection)
    {
        lastClientId = clientConnection.ClientId;
    }
}

public void SendMessageToLastConnection(string message)
{
    var monoBridge = FindObjectOfType<CoherenceMonoBridge>();
    monoBridge.ClientConnections.SendMessage<PlayerConnection>("OnChatMessage",
        lastClientId, MessageTarget.AuthorityOnly, "Hello!");
}

This step is described in detail in the . In short, a Prefab with a CoherenceSync and a custom component (PlayerConnection in this example) must be created and placed in a Resources folder:

PlayerConnection prefab

Client Messages are sent between the . Implementing Client Messages is as simple as creating a command on the CoherenceSync used by the Client Connection Prefab in the CoherenceMonoBridge:

Prefab setup section
commands
Client connection objects
LiveQuery
CoherenceMonoBridge
CoherenceMonoBridge component
MonoBridge with linked connection prefab
Binding a client message