LogoLogo
⚠️ Outdated documentationGo to LatestHomeAPI
SDK 1.0
SDK 1.0
  • Welcome
  • Overview
    • What is coherence?
    • How does coherence work?
    • Rooms and Worlds
    • Features and Roadmap
    • Release Notes
    • Known Issues and Troubleshooting
  • Learning coherence
    • Beginner's Guide to Networking Games
    • 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...
      • Racing
      • Turn-based
      • First-Person Shooter
      • MMO
      • Fighting
  • Get started
    • Installation
    • Scene Setup
      • Samples
    • 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
      • CoherenceBridge
      • CoherenceLiveQuery
      • CoherenceTagQuery
      • Order of execution
    • Asset Management
      • Using CoherenceSyncConfig to instantiate GameObjects locally
      • CoherenceSyncConfigRegistry Save Modes
    • 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
      • Creating your own syncable member
    • 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
    • CLI
    • Upgrading Unity SDK
      • Upgrading to coherence Unity SDK 1.0.0
      • Upgrading to coherence Unity SDK 0.9.0
  • 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
    • Quick Samples
    • Continuous Integration
    • Unreal Engine Support
    • WebGL Support
    • Peer-to-Peer Support (P2P)
    • Pricing
    • SLA
    • Glossary
Powered by GitBook
On this page
  • Our use case
  • The code
  • Changing a synced variable on non-authoritative Clients

Was this helpful?

Export as PDF
  1. Learning coherence
  2. Campfire project

Remote interactions: Trees

Last updated 1 year ago

Was this helpful?

Topics covered

| |

We saw in the previous section about how sometimes it makes sense not to move authority around between Clients. At this point, Network Commands are the way to interact with a remote object.

Now let's take a look at another case of remote object, where the interactions with it need to be validated by the one holding authority, to avoid nasty cases of concurrency.

Our use case

In this project, it is the case of the trees that are placed in the scene. The first Client or Simulator to connect will take authority over them, and it will keep it until they disconnect.

When a player wants to chop a tree, they request the Authority to subtract 1 unit of energy. When the energy runs out, it's the Authority that spawns a new Log instance.

This centralization, as opposed to passing authority around, allows multiple players to chop the same tree at the same time and prevents many race conditions, because the important action (destroying the tree and spawning the log) is all resolved on the Client with Authority.

Conceptually, we can imagine the event flow to go like this:

(1) Chop action happens on a Client -> (2) Authority is notified, elaborates new state -> (3) Authority sends result to all others -> (4) All other Clients play out animation and effects

The code

You can find this flow in practice in the ChoppableTree.cs script. In this script, only one variable is synchronized, the energy of the tree:

[Sync] public int energy = 3;

The flow goes like this:

(1) A player presses the button to chop down the tree.

It locally invokes the method TryChop(), which checks if the tree hasn't been already chopped down, subtracts energy locally, and also invokes the Chop() method, locally or remotely depending if authority on this tree is here or not.

public void TryChop()
{
    if (energy <= 0) return;
    
    if (sync.HasStateAuthority)
        Chop();
    else
    {
        energy--;
        sync.SendCommand<ChoppableTree>(nameof(Chop), MessageTarget.AuthorityOnly);
    }
}

(2) On the Authority, the Chop() method is called, and checks if the tree needs to be effectively cut down based on its energy:

[Command(defaultRouting = MessageTarget.AuthorityOnly)]
public void Chop()
{
    if (energy <= 0) return;
    
    energy--;
    
    if (energy <= 0) CutDown();
}

(3) If so, CutDown() is invoked locally, spawning the log and informing all other clients to play the animation of the tree disappearing:

private void CutDown()
{
    ChangeState(false);
    sync.SendCommand<ChoppableTree>(nameof(ChangeState), MessageTarget.Other, false);

    // Spawns log
    StartCoroutine(GenerateNewLog());
    
    // Will grow the tree back in time
    StartCoroutine(GrowBack());
}

(4) Finally, other Clients play animation, particles and sound locally in ChangeState(). They will also see the log spawn thanks to the automatic network-instantiation.

Changing a synced variable on non-authoritative Clients

Why do we subtract energy from a synced variable in TryChop() when we are not the Authority?

Ultimately, the final word on whether the tree has been chopped down completely is always on the Authority's side, of course. But by subtracting energy locally and immediately, we can deal with cases where the player manages to produce two or more chop inputs before the Network Command has travelled to the Authority (and back) with a result.

Imagine: the tree has 1 energy. If we didn't subtract energy locally, the player would be able to chop several times because until the Authority tells them that the tree is down, they still think it has 1 energy.

In fact, it would send several Chop() Network Commands for no reason, which the Authority would have do discard on arrival.

Instead, if we immediately change the value on the variable and we use it as an indication of whether we can chop or not this will stop the chopping after one hit, as it should be.

Soon, the Authority will have elaborated on its side that the tree has gone down, and will inform our Client (with ChangeState()). Because energy is a synced variable, it will be overwritten again with the value computed on the Authority - which of course will be 0 at this point, so it will match.

So nothing is lost and no state is compromised, but with this little trick we get immediate feedback and we avoid some unneeded network traffic.

Authority
Authority transfer
Network Commands
sitting on chairs
A player about to interact with a remote tree