Example – a global counter

This document explains how to set up an ever increasing counter that all Clients have access to. This could be used to make sure that everyone can generate unique identifiers, with no chance of ever getting a duplicate.

By being persistent, the counter will also keep its value even if all Clients log off, as long as the Replication Server is running.

The Counter

First, create a script called Counter.cs and add the following code to it:

using UnityEngine;
using Coherence;
using Coherence.Toolkit;

public class Counter : MonoBehaviour
{
    public int counter = 0;
    public NumberRequester requester;

    public void NextNumber(CoherenceSync requester)
    {
        requester.SendCommand<NumberRequester>(
            nameof(NumberRequester.GotNumber),
            MessageTarget.AuthorityOnly,
            counter);
        counter++;
    }
}

This script expects a command sent from a script called NumberRequester, which we will create below.

Next, add this script to a Prefab with CoherenceSync on it, and select the counterand the method NextNumber for syncing in the bindings window. To make the counter behave like we want, mark the Prefab as "Persistent" and give it a unique persistence ID, e.g. "THE_COUNTER". Also change the adoption behaviour to "Auto Adopt":

Finally, make sure that a single instance of this Prefab is placed in the scene.

NumberRequester

Now, create a script called NumberRequester.cs. This will be an example MonoBehaviour that requests a unique number by sending the command GetNumber to the Counter Prefab. As a single argument to this command, the NumberRequester will send an entity reference to itself. This makes it possible for the Counter to send back a response command (GotNumber) with the number that was generated. In this simple example we just log the number to the console.

using UnityEngine;
using Coherence;
using Coherence.Toolkit;

public class NumberRequester : MonoBehaviour
{
    CoherenceSync sync;

    private void Awake()
    {
        sync = GetComponent<CoherenceSync>();
    }

    void Update()
    {
        if (sync.HasStateAuthority && Input.GetKeyDown(KeyCode.Return))
        {
            var counter = FindAnyObjectByType<Counter>();
            var counterSync = counter.GetComponent<CoherenceSync>();

            counterSync.SendCommand<Counter>(
                nameof(Counter.NextNumber),
                MessageTarget.AuthorityOnly,
                sync);
        }
    }

    public void GotNumber(int number)
    {
        Debug.Log($"Got number: {number}");
    }
}

To make this script work, add it to a Prefab that has the CoherenceSync script and mark the GotNumber for syncing in the bindings window.

Last updated