Skip to content

feat: local iteration workflows - testing multiplayer games locally doc #263

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Sep 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
203 changes: 203 additions & 0 deletions docs/advanced-topics/networktime-ticks.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
---
id: networktime-ticks
title: NetworkTime and Ticks
sidebar_label: NetworkTime & Ticks
---

## LocalTime and ServerTime

Why are there two different time values and which one should be used?

Netcode for Gameobjects uses a star topology. That means all communications happen between the clients and the server/host and never between clients directly. Messages take time to transmit over the network. That's why `RPCs` and `NetworkVariable` will not happen immediately on other machines. `NetworkTime` allows to use time while considering those transmission delays.

- `LocalTime` on a client is ahead of the server. If a server RPC is sent at `LocalTime` from a client it will roughly arrive at `ServerTime` on the server.
- `ServerTime` on clients is behind the server. If a client RPC is sent at `ServerTime` from the server to clients it will roughly arrive at `ServerTime` on the clients.



<Mermaid chart={`
sequenceDiagram
participant Owner as Client LocalTime
participant Server as Server ServerTime & LocalTime
participant Receiver as Client ServerTime
Note over Owner: Send message to server at LocalTime.
Owner->>Server: Delay when sending message
Note over Server: Message arrives at ServerTime.
Note over Server: On server: ServerTime == LocalTime.
Note over Server: Send message to clients at LocalTime.
Server->>Receiver: Delay when sending message
Note over Receiver: Message arrives at ServerTime.
`}/>




`LocalTime`
- Use for player objects with client authority.
- Use if just a general time value is needed.

`ServerTime`:
- For player objects with server authority (E.g. by sending inputs to the server via RPCs)
- In sync with position updates of NetworkTransform for all NetworkObjects where the client is not authoritative over the transform.
- For everything on non client controlled NetworkObjects.

## Examples

### Example 1: Using network time to synchronize environments

Many games have environmental objects which move in a fixed pattern. By using network time these objects can be moved without having to synchronize their positions with a `NetworkTransform`.

For instance the following code could be used to create a moving elevator platform for a client authoritative game:

```csharp
using Unity.Netcode;
using UnityEngine;

public class MovingPlatform : MonoBehaviour
{
public void Update()
{
// Move up and down by 5 meters and change direction every 3 seconds.
var positionY = Mathf.PingPong(NetworkManager.Singleton.LocalTime.TimeAsFloat / 3f, 1f) * 5f;
transform.position = new Vector3(0, positionY, 0);
}
}
```

### Example 2: Using network time to create a synced event

Most of the time aligning an effect precisely to time is not needed. But in some cases for important effects or gameplay events it can help to improve consistency especially for clients with bad network connections.

```csharp
using System.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Assertions;

public class SyncedEventExample : NetworkBehaviour
{
public GameObject ParticleEffect;

// Called by the client to create a synced particle event at its own position.
public void ClientCreateSyncedEffect()
{
Assert.IsTrue(IsOwner);
var time = NetworkManager.LocalTime.Time;
CreateSyncedEffectServerRpc(time);
StartCoroutine(WaitAndSpawnSyncedEffect(0)); // Create the effect immediately locally.
}

private IEnumerator WaitAndSpawnSyncedEffect(float timeToWait)
{
// Note sometimes the timeToWait will be negative on the server or the receiving clients if a message got delayed by the network for a long time. This usually happens only in rare cases. Custom logic could be implemented to deal with that scenario.
if (timeToWait > 0)
{
yield return new WaitForSeconds(timeToWait);
}

Instantiate(ParticleEffect, transform.position, Quaternion.identity);
}

[ServerRpc]
private void CreateSyncedEffectServerRpc(double time)
{
CreateSyncedEffectClientRpc(time); // Call a client RPC to also create the effect on each client.
var timeToWait = time - NetworkManager.ServerTime.Time;
StartCoroutine(WaitAndSpawnSyncedEffect((float)timeToWait)); // Create the effect on the server but wait for the right time.
}

[ClientRpc]
private void CreateSyncedEffectClientRpc(double time)
{
// The owner already created the effect so skip them.
if (IsOwner == false)
{
var timeToWait = time - NetworkManager.ServerTime.Time;
StartCoroutine(WaitAndSpawnSyncedEffect((float)timeToWait)); // Create the effect on the client but wait for the right time.
}
}
}
```

<Mermaid chart={`
sequenceDiagram
participant Owner as Owner
participant Server as Server
participant Receiver as Other Client
Note over Owner: LocalTime = 10.0
Note over Owner: ClientCreateSyncedEffect()
Note over Owner: Instantiate effect immediately (LocalTime = 10)
Owner->>Server: CreateSyncedEffectServerRpc
Server->>Receiver: CreateSyncedEffectClientRpc
Note over Server: ServerTime = 9.95 #38; timeToWait = 0.05
Note over Server: StartCoroutine(WaitAndSpawnSyncedEffect(0.05))
Server->>Server: WaitForSeconds(0.05);
Note over Server: Instantiate effect at ServerTime = 10.0
Note over Receiver: ServerTime = 9.93 #38; timeToWait = 0.07
Note over Receiver: StartCoroutine(WaitAndSpawnSyncedEffect(0.07))
Receiver->>Receiver: WaitForSeconds(0.07);
Note over Receiver: Instantiate effect at ServerTime = 10.0
`}/>



:::note
Some components such as `NetworkTransform` add additional buffering. When trying to align an RPC event like in this example, an additional delay would need to be added.
:::

## Network Ticks

Network ticks are run at a fixed rate. The 'Tick Rate' field on the NetworkManager can be used to set the tick rate.

What does changing the network tick affect? Changes to `NetworkVariables` are not sent immediately. Instead during each network tick changes to `NetworkVariables` are collected and sent out to other peers.

To run custom code once per network tick (before `NetworkVariable` changes are collected) the `Tick` event on the `NetworkTickSystem` can be used.
```cs
public override void OnNetworkSpawn()
{
NetworkManager.NetworkTickSystem.Tick += Tick;
}

private void Tick()
{
Debug.Log($"Tick: {NetworkManager.LocalTime.Tick}");
}

public override void OnNetworkDespawn() // don't forget to unsubscribe
{
NetworkManager.NetworkTickSystem.Tick -= Tick;
}
```

:::tip
When using `FixedUpdate` or physics in your game, set the network tick rate to the same rate as the fixed update rate. The `FixedUpdate` rate can be changed in `Edit > Project Settings > Time > Fixed Timestep`
:::

## Network FixedTime

`Network FixedTime` can be used to get a time value representing the time during a network tick. This works similar to `FixedUpdate` where `Time.fixedTime` represents the time during the `FixedUpdate`.

```cs
public void Update()
{
double time = NetworkManager.Singleton.LocalTime.Time; // time during this Update
double fixedTime = NetworkManager.Singleton.LocalTime.FixedTime; // time during the previous network tick
}
```

## NetworkTime Precision

Network time values are calculated using double precisions. This allows time to stay accurate on long running servers. For game servers which run sessions for a long time (multiple hours or days) do not convert this value in a float and always use doubles for time related calculations.

For games with short play sessions casting the time to float is safe or `TimeAsFloat` can be used.

## NetworkTimeSystem Configuration

:::caution
The properties of the `NetworkTimeSystem` should be left untouched on the server/host. Changing the values on the client is sufficient to change the behavior of the time system.
:::

The way network time gets calculated can be configured in the `NetworkTimeSystem` if needed. See the API docs (TODO LINK) for information about the properties which can be modified. All properties can be safely adjusted at runtime. For instance buffer values could be increased for a player with a bad connection.

<!-- On page code -->

Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
---
id: local_iteration_testing_locally
title: Local Iteration - Testing multiplayer games locally
description: Guide covering the available workflows for testing multiplayer games locally.
---
- [Player Builds](#player-builds)
- [Local iteration using Player Builds](#local-iteration-using-player-builds)
- [ParrelSync](#parrelsync)
- [Installation](#installation)
- [Usage](#usage)
- [Known issues and workarounds](#known-issues-and-workarounds)
- [General tips](#general-tips)

Testing a multiplayer game presents unique challenges to developers:
- We need to run multiple instances of the game in order to test multiplayer scenarios.
- We also need to iterate quickly on our custom code and asset changes and validate our work in a multiplayer scenario.
- We need to be able to debug our work in a multiplayer scenario using editor tools.

Currently, Unity does not provide any workflow that covers all of these requirements. (See our [roadmap here](https://unity.com/roadmap/unity-platform/multiplayer-networking))

There will always be a need to validate our work in the target distribution format (ie. on platform) and the way to do it is by creating [Player Builds](#player-builds).

However, player builds do not meet the requirement of quick iteration and easy debuggability using editor tools. As such our current recommended workflow for local iteration [ParrelSync](#parrelsync).

## Player Builds

:::hint

This approach is great when we need to verify our work on the target platform or with a wider group of testers.

:::

First we need to build an executable. The default way of doing that is via `File->Build Settings` in the menu bar, and then pressing `Build` button.

Then the build can be shared among the testers.

### Local iteration using Player Builds

Once the build has completed you can launch several instances of the built executable in order to both host and join a game.

It is also possible to run the builds along with an editor that produced said build, which could be useful during iterations.

> Mac users: to run multiple instances of the same app, you need to use the command line.
> Run `open -n YourAppName.app`

:::hint

Though functional, we find this approach to be somewhat slow for the purposes of local iteration. Head on to the [ParrelSync](#parrelsync) section for our suggested workflow for local iteration.

:::

## ParrelSync
![parrelsync-bossroom-demo](../../../static/img/parrelsync-bossroom-demo.gif)

[**ParrelSync**](https://github.com/VeriorPies/ParrelSync) is an open-source Unity editor extension that allows users to **test multiplayer gameplay without building the project** by having another Unity editor window opened and mirror the changes from the original project.

**ParrelSync** works by making a copy of the original project folder and creating symbolic links to the `Asset` and `Project Settings` folders back from the original project.

We use **ParrelSync** for local iteration in [BossRoom sample](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/).

:::important

**ParrelSync** relies on symbolic links and partial copies of the original project folder structure - generally it is completely safe.

Yet, just to be sure that no bug in any of the software you use can destroy your work - it's a good idea to consistently backup your project or use a version control system such as [Git](https://git-scm.com/), [SVN](https://subversion.apache.org/), [Plastic](https://www.plasticscm.com/) or any other.

:::

### Installation

Follow the installation instructions on **ParrelSync** repo [page](https://github.com/VeriorPies/ParrelSync#installation)

### Usage
- Open the `ParrelSync->Preferences` menu in the menu bar to open the preferences window
- Verify that your settings are set to the following: ![parrelsync-preferences](../../../static/img/parrelsync-preferences.png)

:::important

By default **ParrelSync** prevents asset serialization in all clone instances and changes can only be made from the original project editor. This is a **very important setting** that prevents issues with multiple editors accessing the same `Library` folder (which is not supported and breaks basic assumptions in Unity design).

:::

- Open the `ParrelSync->Clones Manager` from which you can launch, create and remove clone editors.
- Advanced usage is to utilize **ParrelSync's** capability of passing [Arguments](https://github.com/VeriorPies/ParrelSync/wiki/Argument) to clones, thus allowing to run custom logic on a per-clone basis.

### Known issues and workarounds
- An important nuance is that **ParrelSync** does not sync changes made to packages. `Packages` folder is synced on clone opening, so if you made package changes - you should close and re-open your clones.
- [Relevant GitHub issue](https://github.com/VeriorPies/ParrelSync/issues/48)
- If you encounter a Netcode error that mentions `soft sync` - that generally means that prefabs or scenes are not in sync between editors. You should save the project in the main editor via `File->Save Project` and refresh the projects in the clone editors by pressing `Ctrl + R` (which is by default done automatically) or reimport networked prefabs in the main editor.
- More information and general **ParrelSync** FAQ: https://github.com/VeriorPies/ParrelSync/wiki/Troubleshooting-&-FAQs
- The ultimate workaround in case nothing helps - deleting and re-creating the clone instance via `ParrelSync->Clones Manager` window.

## General tips
- Bigger screens or multi-screen setups allow for more screen real estate, which is handy when one has to have multiple instances of an app opened at the same time.
- **ParrelSync** has to copy and update separate `Packages` and `Library` folders for every clone, and in certain cases a fix for misbehaving clone is re-creation - a good SSD makes this process quite a bit faster.
- Creating a fork of any git repository that your project relies upon in production could help avoid bad surprises if the repo gets taken down or introduces an undesirable change. You should fork **ParrelSync** before using it in your live project.
11 changes: 11 additions & 0 deletions sidebars.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,17 @@ module.exports = {
],

},
{
"collapsed": true,
"type": "category",
"label": "Local Iteration ",
"items": [
{
"type": "doc",
"id": "tutorials/local_iteration_series/local_iteration_testing_locally"
}
],
},
{
"collapsed": true,
"type": "category",
Expand Down
Binary file added static/img/parrelsync-bossroom-demo.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added static/img/parrelsync-preferences.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,4 @@ In all `NetworkUpdateStages`, it iterates over a static array and calls the `Net

## References

See [Network Update Loop Reference](network-update-loop-reference.md) for process flow diagrams and code.
See [Network Update Loop Reference](network-update-loop-reference.md) for process flow diagrams and code.
Original file line number Diff line number Diff line change
Expand Up @@ -152,5 +152,4 @@ A tick or simulation rate of 60Hz will cause less delay than a tick rate of 30Hz

When a server gets close to the limit, or even fails to process a tick inside that timeframe, then you will instantly notice the results: all sorts of strange gameplay issues like rubber banding, players teleporting, hits getting rejected, and physics failing.


import ImageSwitcher from '@site/src/ImageSwitcher.js';