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
  • Controls
  • Topics covered
  • In this scene
  • How it's set up
  • Simulating lifetime without a Simulator
  • Destroying other Clients' flowers

Was this helpful?

Export as PDF
  1. Learning coherence
  2. First Steps tutorial

6. Persistence

Last updated 1 year ago

Was this helpful?

We have seen a lot of examples with objects belonging to a Client, and when that Client disconnects, they disappear with them. We call these session-based entities.

But coherence also has a built-in system to make objects survive the disconnection of a Client, and be ready to be adopted by another Client or a Simulator. We call these objects persistent. Persistent objects stay on the Replication Server even if no Client is connected, creating the feeling that the game world is alive beyond an individual player session.

Controls

  • WASD or Left stick: Move character

  • Hold Shift or Shoulder button left: Run

  • P or Right shoulder button: Plant a flower (hold to preview placement)

Topics covered

| |

In this scene

Players can plant flowers in this little valley. Each flower has 3 phases: starts as a bud, blooms into a full flower, and then withers after some time.

Creating a flower generates a new, persistent network entity. Even if the Client disconnects, the flower will persist on the server. When they reconnect, they will see the flower at their correct stage of growth (this is a little trick ).

Planting too many flowers starts erasing older flowers. A button in the UI allows clearing all flowers (belonging to any player) at any time.

How it's set up

When using the plant action, any connected player instantiates a copy of the Flower Prefab (located in the /Prefabs/Nature folder).

By selecting the Prefab asset, we can see its CoherenceSync component is set up like this:

In particular, notice how the Lifetime property is set to Persistent. This means that when the Client who plants a flower disconnects, the network entity won't be automatically destroyed. Auto-adopt Orphan set to on makes it so the next player who sees the flower instantly adopts it, and keeps simulating its growth.

Opening coherence's Configuration window, you will see that we sync position, rotation, and a variable called timePlanted:

Once a flower has spawned, all of its logic runs locally (no coherence involved). An internal timer calculates what phase it should be in by looking at the timePlanted property and doing the math, and playing the appropriate animations and particles as a result.

Simulating lifetime without a Simulator

To achieve this, the flowers of this scene store the Flower.timePlanted value on the Replication Server. A Replication Server with no connected Clients is dormant, and has a very low cost to run. So when nobody's connected the flowers are not actually simulating, they are just waiting.

When a new Client comes online and this value is synced to them, they immediately fast-forward the phase of the flower to the correct value, and then they start simulating locally as normal.

This gives the players the perception that things are still running even when they are not connected.

This setup is not bulletproof, and could be easily cheated if a player comes online with a modified Client, changing the algorithm calculating the flowers' phase.

But for a game in which this calculation is not critical, especially if it doesn't affect other player's experience of the game, this can be a nice setup to cut some costs.

Destroying other Clients' flowers

Every Client can, at any time, remove all flowers from the scene by clicking a button in the UI.

It's important to remember that you shouldn't call Destroy() on a network entity on which the Client doesn't have authority on. To achieve this, we first request authority on remote flowers and listen for a reply. Once obtained it, we destroy them.

Check the code at the end of the Flower script:

public void DestroyRemote()
{
    _sync = GetComponent<CoherenceSync>();
    _sync.OnStateAuthority.AddListener(DestroyThis);
    _sync.RequestAuthority(AuthorityType.Full);
}

private void DestroyThis()
{
    _sync.OnStateAuthority.RemoveListener(DestroyThis);
    Destroy(gameObject, .1f);
}

When it gets instantiated, the flower writes the current into the timePlanted variable. This variable never changes after this, and is used to reconstruct the phase in which the flower is in (see ). Similarly, as the flower is not moving, position and rotation are only synced at the time of planting.

coherence supports the ability to have an instance of the game active in the cloud, running some logic all the time (we call this a ). However, this might be an expensive setup, and it's good advice to think things through differently to keep the cost of running your game lower.

As we discussed in the , switching authority is a network operation that is asynchronous, so we need to wait for the reply from the player who currently has authority.

Simulator
Physics lesson
UNIX timestamp
below
Persistence
Simulator
Requesting authority
we explain later
A player about to plant a new flower, surrounded by flowers in different stages.
The Flower Prefab's CoherenceSync.
The setup of the Flower Prefab.
The button to clear the flowers.