# 6. Persistence

We have seen a lot of examples where objects belonging to a Client would disappear with them when they disconnect. We call these objects **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.

{% tabs %}
{% tab title="Topics covered" %}
[Persistence](https://docs.coherence.io/manual/lifetime/persistence) | [Simulator](https://docs.coherence.io/manual/simulation-server) | [Requesting authority](https://docs.coherence.io/manual/authority)
{% endtab %}

{% tab title="Game 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)
  {% endtab %}
  {% endtabs %}

## 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 [we explain later](#simulating-offline-without-a-simulation-server)).

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

<figure><img src="https://content.gitbook.com/content/CMCtKgV0bk1lwR4tWK3W/blobs/nStZ8G8WsxsDnAs3mEmd/PlantingFlowers.png" alt=""><figcaption><p>A player about to plant a new flower, surrounded by flowers in different stages.</p></figcaption></figure>

## 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:

<figure><img src="https://content.gitbook.com/content/CMCtKgV0bk1lwR4tWK3W/blobs/tod5VZTN47RiNQm36izZ/FlowerSync.png" alt=""><figcaption><p>The Flower Prefab's CoherenceSync.</p></figcaption></figure>

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`:

<figure><img src="https://content.gitbook.com/content/CMCtKgV0bk1lwR4tWK3W/blobs/2eAiivREUgvCt4jFAcmY/FlowerVariables.png" alt=""><figcaption><p>The setup of the Flower Prefab.</p></figcaption></figure>

When it gets instantiated, the flower writes the current [UNIX timestamp](https://www.unixtimestamp.com/) into the `timePlanted` variable. This variable never changes after this, and is used to reconstruct the phase in which the flower is in (see [below](#simulating-lifetime-without-a-simulation-server)). Similarly, as the flower is not moving, position and rotation are only synced at the time of planting.

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

**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 [Simulator](https://docs.coherence.io/manual/simulation-server)). 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.

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.

{% hint style="info" %}
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.
{% endhint %}

### Destroying other Clients' flowers

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

<figure><img src="https://content.gitbook.com/content/CMCtKgV0bk1lwR4tWK3W/blobs/pda7gaJPHIxGLshYXXDY/ClearFlowers.png" alt=""><figcaption><p>The button to clear the flowers.</p></figcaption></figure>

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:

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

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

As we discussed in the [Physics lesson](https://docs.coherence.io/getting-started/samples-and-tutorials/first-steps-tutorial/2-physics-authority-transfer), switching authority is a network operation that is asynchronous, so we need to wait for the reply from the player who currently has authority.
