LogoLogo
HomeOnline DashboardAPIDiscordForums
SDK 0.5.2
SDK 0.5.2
  • Welcome
  • Overview
    • What is coherence?
    • How does coherence work?
    • Features and Roadmap
    • Requirements
  • Get Started
    • Install coherence
    • Scene setup
    • Prefab setup
    • Build and run
    • Baking and code generation
    • Create a free account
    • Deploy replication server
    • Share builds
  • Authority and communication
    • How authority works
    • Authority transfer
    • Commands
    • Client messages
    • Server-side and input queues
    • Animations
  • Persistence
    • Overview
    • Configuring persistence
    • Storage
    • Example – A global counter
  • Optimization
    • Overview
    • Simulation frequency
    • Areas of interest
    • World size
    • Level of detail
    • Interpolation
    • Extrapolation
  • Connected entities
    • Overview
    • Entity references
    • Parent-child relationships
  • Simulators
    • Overview
    • Client vs. simulator logic
    • Build and deploy
    • Simulator load balancing
  • Tutorial project
    • Get the Tutorial Project
    • Start Tutorial
      • 1. Transforms
      • 2. Physics
      • 3. Persistence
      • 4. Animation and Variables
      • 5. AI Navigation
      • 6. Network Commands
      • 7. Network Teams (draft)
  • Game Services
    • Game account
    • Key-value store
    • Matchmaking
  • Developer Portal
    • Overview
    • Dashboard
    • Resource Usage
    • Replicator and Simulator Configuration
    • Enabling Game Services
  • API reference
    • Network SDK
      • CoherenceSync
      • MonoBridge
      • LiveQuery
      • Archetype
      • Sample UI
      • Settings Window
      • Custom Bindings
    • Cloud API
      • API tokens and keys
      • Server discovery
      • Game account
      • Key-value store
      • Matchmaking
    • Replication Server
    • Simulation Server
  • Schema reference
    • Overview
    • Specification
    • Field Settings
    • Archetypes and LOD-ing
  • Resources
    • Downloads
    • SDK Update Guide
    • Video Tutorials
    • Glossary
    • CLI Utilities
    • Helper Scripts
    • Troubleshooting
  • Community
    • Discord
  • Additional information
    • Pricing
    • SLA
    • Unreal Engine support
    • WebGL
    • Peer-to-Peer (P2P)
    • Known Issues
    • Changelog
Powered by GitBook
On this page
  • The Counter
  • NumberRequester

Was this helpful?

Export as PDF
  1. Persistence

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.Toolkit;

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

    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.Toolkit;

public class NumberRequester : MonoBehaviour
{
    CoherenceSync sync;

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

    void Update()
    {
        if(sync.isSimulated && Input.GetKeyDown(KeyCode.Return))
        {
            var counter = FindObjectOfType<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 3 years ago

Was this helpful?

CoherenceSync inspector