-
Notifications
You must be signed in to change notification settings - Fork 216
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
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
88d3b67
Adding a local iteration guide doc
pdeschain 9377e78
admonition instead of quote
pdeschain 83ee44d
a less chonky gif
pdeschain 11a7d4f
sidebar
pdeschain e9dbdc2
Apply suggestions from code review
pdeschain 7164ac0
Merge branch 'master' into pdeschain/local-iteration-workflows
Briancoughlin f752c21
MTTDOC-317 updates to enable building of site
Briancoughlin f8f4aa4
Changes based on PR feedback p1
pdeschain 8f5243f
Update local-Iteration-testing-multiplayer-games-locally.md
Briancoughlin 291b88e
addressing comments
pdeschain e7ad90e
Merge branch 'pdeschain/local-iteration-workflows' of https://github.…
pdeschain f736bcd
linked to parrelsync issue ticket
pdeschain 2b179b5
#
pdeschain 3ac7309
Update docs/tutorials/local_iteration_series/local-Iteration-testing-…
pdeschain 9194442
Merge branch 'master' into pdeschain/local-iteration-workflows
s-omeilia-unity File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 --> | ||
|
96 changes: 96 additions & 0 deletions
96
...als/local_iteration_series/local-Iteration-testing-multiplayer-games-locally.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
pdeschain marked this conversation as resolved.
Show resolved
Hide resolved
|
||
 | ||
|
||
[**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:  | ||
|
||
:::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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.