Skip to content

Commit b0693ab

Browse files
jy-vivoxjabbacakesNoelStephensUnity
authored
feat: add Unity CLI commands for Netcode for GameObjects (MTT-16534) (#4210)
* feat: add Unity CLI commands for Netcode for GameObjects (MTT-16534) Commands in the netcode.gameobjects groups for com.unity.pipeline 0.9.0 or later: set up NetworkManagers and network prefabs, audit the project, start and stop sessions, inspect clients and spawned objects, spawn, despawn and change ownership, simulate network conditions and sample network traffic. The command assembly only compiles when the pipeline package is installed; the logic lives in the editor assembly and is tested without it. * fix: gate the CLI commands on com.unity.pipeline 0.9.0-exp.1 (MTT-16534) A prerelease sorts below its release, so the 0.9.0 gate left the commands out of projects with the published 0.9.0-exp.1. * fix: clean up the CLI commands (MTT-16534) Restore each transport's own simulator settings once the CLI simulator, timeout and lag spike are off, and keep a timeout on through a lag spike. Gate the simulator presets on Multiplayer Tools 2.0. Prefer an exact NetworkManager name, keep the transport protocol and WebSocket path when setting the address, refuse address changes on Relay, and listen on every interface for a remote address. Let the server own objects in client-server. * fix: address review of the CLI prefab and config commands (MTT-16534) - register_prefab treats a prefab as registered when a list entry overrides it, matching entries by source prefab or prefab id hash as NGO does at runtime. - audit reports override entries with no target, a target without a root NetworkObject, or a hash override with a zero source hash. - audit, list_prefabs and register_prefab handle empty list entries; audit reports them as a LIST_ENTRY_INVALID warning. - make_prefab refuses prefabs with child NetworkObjects instead of saving an unsupported network prefab. - config set refuses spawn_timeout outside 10-3600 seconds, and NaN or infinite float values. * fix: CLI issues found in two-editor testing (MTT-16534) - profiler get_stats reads traffic from the message manager's hooks, as NGO's own metrics do: bytes and messages sent and received, per message type. The profiler's Network counters it read before stayed at zero in a live session. - session reconnect connects a client again after it was kicked or timed out, instead of refusing because it had already shut down. - Messages name an unsaved scene as such instead of leaving the name blank. * fix: CLI audit flags hybrid prefab overrides and counts hash overrides as registration (MTT-16534) * fix: address review of the CLI config, spawn, stats, audit and get_object commands (MTT-16534) - config set records changes to a prefab instance as prefab overrides in edit mode. - spawn refuses a distributed-authority client that hasn't connected yet, and destroys an instance a failed spawn leaves behind. - get_stats ends with an error when the session stops or restarts while sampling. - audit counts the open scenes' player prefabs as registered, and ignores the Prefab field a hash override keeps, as NGO does. - get_object lists only the inspected object's own behaviours, not nested ones. * fix: rename the CLI assemblies for the package naming rule, and keep Unity null checks in SourcePrefab (MTT-16534) - Unity.Netcode.GameObjects.Editor.CLI becomes Unity.Netcode.GameObjects.CLI.Editor and its tests Unity.Netcode.GameObjects.CLI.Editor.Tests, as package validation (PVP-132-2) requires editor assemblies to end with .Editor and editor test assemblies with .Editor.Tests. - SourcePrefab tests the override source with Unity's null check in a form the standards check accepts; its suggested ?? would skip that check for a missing reference. * Apply batched suggestions from code review Co-authored-by: Amy Reeve <amy.reeve@unity3d.com> * test: cover reconnect, a remote client, a port override and the distributed authority spawn refusal in the CLI queries (MTT-16534) * test: exit play mode after a failing CLI play mode test, and take test ports from the OS (MTT-16534) - A [UnityTearDown] shuts down running NetworkManagers and exits play mode, so a failed assert no longer leaves the following edit mode tests in play mode. - Enter play mode options are only changed (and restored) when they differ, so ProjectSettings/EditorSettings.asset isn't re-saved. - The play mode tests bind a port the OS reports as free instead of a random one in 20000-40000. * fix: hook the CLI network simulator into transports only once it's turned on, and warn in the console while it is (MTT-16534) - UnityTransport.TransportInitialized is subscribed to only when the CLI simulator, a timeout or a lag spike is on, so projects that never use the CLI hook no transport event. - While the simulator is on, the console warns once per play session, when it first changes a driver, with the delay, jitter and loss and how to turn it off. The settings outlast the play session that set them. - The hook stays in the editor assembly: the query layer and its tests use it, and the CLI assembly only compiles with com.unity.pipeline. * fix: say when the CLI transport, simulator and stats commands don't reach a hybrid session (MTT-16534) A session whose prefabs include GhostObject ones runs over Netcode for Entities' UnifiedNetcodeTransport on port 7979, not the NetworkManager's UnityTransport. - simulator get and set add a note for such managers, and timeout and lag_spike refuse with that reason instead of asking for a session to be started. - config set address, port and listen_address still save the value, with a note that it doesn't apply. session start skips its address and port override and says why. - get_stats notes that GhostObject replication isn't counted. - The audit's hybrid prefab lookup is shared as ConfiguredHybridPrefabs, so a session is recognized as hybrid before it starts. - The docs add a Hybrid sessions section that points to Netcode for Entities' netcode.simulator and netcode.profiler commands. * fix: keep LAN hosts reachable, refuse to reconnect a stopped host, and only lift a blackout the CLI set (MTT-16534) - config set address and session start --address move a default listen address with the connect address, as create_network_manager sets it, so a host on a LAN address listens on 0.0.0.0. A listen address set on purpose stays. - reconnect refuses a host or server the CLI started and that has since stopped, instead of starting it again as a client. - The simulator lifts leftover 100% packet loss only when the CLI applied it (tracked in SessionState), so loss set on purpose in a Network Simulator component stays. - UnityTransport exposes an internal TransportId, used for its driver events and by the CLI simulator, instead of the simulator copying the computation. - config set no longer creates a missing NetworkConfig before the dry-run check; it refuses instead. * docs: note the received-bytes overcount in get_stats, say register_prefab saves the list, and add the PR number to the changelog (MTT-16534) - get_stats' docs and receive hook note that per-type received bytes can be up to 6 bytes a message high, because NetworkMessageManager reports the unpacked header size. Batch totals are exact. - register_prefab's description and docs say it saves the list and creates the default list if needed. - The CHANGELOG entry gets (#4210). * refactor: remove Linq from the CLI query layer and its tests (MTT-16534) - Loops and List/Array methods (Find, FindAll, Exists, ConvertAll, GetRange) replace every Linq call in Editor/CliQueries and Tests/Editor/Cli. - New helpers keep the output unchanged: StableSort keeps OrderBy's tie order for managers, spawned objects and stats messages. WithoutDuplicates keeps Distinct's first-seen order. JoinNames builds the comma-separated lists in messages. - Session's IsConnected and CountOtherClients replace the hidden Linq Contains and Count on ConnectedClientsIds. * fix: address code review of the CLI review fixes (MTT-16534) - NetworkManager keeps the role it last started as (internal LastStartedRole), so reconnect refuses a stopped host or server however it was started, and the CLI's own role dictionary, and its leak, is gone. - The simulator forgets a blackout only once every live driver has been let through, so timeout false still lifts one left on after a script recompile in play mode. - After a recompile in play mode, the simulator subscribes to new drivers again when it's on. - The console warns again when the simulator settings change, instead of keeping the first values. - config set address/port explains a hybrid session when the transport has already been swapped to UnifiedNetcodeTransport. - A distributed authority manager isn't reported as hybrid, since that topology rejects hybrid prefabs. - Start's doc comment is back on Start. * fix: simplify two qualified names in the CLI query tests for the standards check (MTT-16534) - UnifiedNetcodeTransport is written as Unified.UnifiedNetcodeTransport, since the tests' namespace is already under Unity.Netcode (IDE0001). - The m_Hooks lookup uses BindingFlags directly now that the file has using System.Reflection (IDE0002). --------- Co-authored-by: Amy Reeve <amy.reeve@unity3d.com> Co-authored-by: Noel Stephens <noel.stephens@unity3d.com>
1 parent 3c8364b commit b0693ab

40 files changed

Lines changed: 5228 additions & 10 deletions

‎com.unity.netcode.gameobjects/CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ Additional documentation and release notes are available at [Multiplayer Documen
1010

1111
### Added
1212

13+
- Added Unity CLI commands (`netcode.gameobjects` groups) to set up NetworkManagers and network prefabs, start and stop sessions, inspect clients and spawned objects, spawn, despawn and change ownership, simulate network conditions and sample network traffic. They are available when the project has `com.unity.pipeline` 0.9.0-exp.1 or later. (#4210)
1314
- Added alignment of the Netcode for Entities tick rates with `NetworkConfig.TickRate` when a session carrying `GhostObject` prefabs is started, so `GhostObject` updates land on the same interval as the rest of Netcode for GameObjects. (#4144)
1415
- Added `NetworkConfig.AutoConfigureSnapshotSize`, enabled by default, which sets the Netcode for Entities snapshot packet size to 4096 bytes when a session carrying `GhostObject` prefabs is started. Netcode for Entities defaults to a single MTU, which updates `GhostObject`s well below the tick rate at the instance counts Netcode for GameObjects projects typically run. Disable it to manage the value yourself. (#4144)
1516

‎com.unity.netcode.gameobjects/Documentation~/TableOfContents.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@
103103
* [Logging](basics/logging.md)
104104
* [Techniques and tricks for debugging multiplayer games](tutorials/testing/techniques_and_tricks_for_debugging_multiplayer_games.md)
105105
* [Command-line helper](tutorials/command-line-helper.md)
106+
* [Unity CLI commands](unity-cli-commands.md)
106107
* [Troubleshooting](troubleshooting/troubleshooting.md)
107108
* [Error messages](troubleshooting/error-messages.md)
108109
* [FAQ](learn/faq.md)

‎com.unity.netcode.gameobjects/Documentation~/testing-debugging.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,5 +10,6 @@ Understand how to set up session management in Netcode for GameObjects.
1010
| **[Logging](basics/logging.md)** | In a multiplayer game, clients might get disconnected from the server for a variety of reasons (such as network issues or application/device crashes). For those reasons, you might want to allow your players to reconnect to the game. |
1111
| **[Techniques and tricks for debugging multiplayer games](tutorials/testing/techniques_and_tricks_for_debugging_multiplayer_games.md)** | In a multiplayer game, clients might get disconnected from the server for a variety of reasons (such as network issues or application/device crashes). For those reasons, you might want to allow your players to reconnect to the game. |
1212
| **[Command-line helper](tutorials/command-line-helper.md)** | In a multiplayer game, clients might get disconnected from the server for a variety of reasons (such as network issues or application/device crashes). For those reasons, you might want to allow your players to reconnect to the game. |
13+
| **[Unity CLI commands](unity-cli-commands.md)** | Drive Netcode for GameObjects from the command line, CI, or an AI agent: set up NetworkManagers and prefabs, run sessions, inspect clients and objects, and simulate network conditions. |
1314
| **[Troubleshooting](troubleshooting/troubleshooting.md)** | In a multiplayer game, clients might get disconnected from the server for a variety of reasons (such as network issues or application/device crashes). For those reasons, you might want to allow your players to reconnect to the game. |
1415
| **[Error messages](troubleshooting/error-messages.md)** | In a multiplayer game, clients might get disconnected from the server for a variety of reasons (such as network issues or application/device crashes). For those reasons, you might want to allow your players to reconnect to the game. |
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
# Unity CLI commands
2+
3+
Drive Netcode for GameObjects from the command line, a CI job, or an AI agent with the [Unity CLI](https://docs.unity.com/en-us/unity-cli/unity-cli). You can use commands to set up a NetworkManager and network prefabs, start and stop sessions, inspect connected clients and spawned objects, simulate poor network conditions, and sample network traffic.
4+
5+
To use Unity CLI commands with Netcode for GameObjects, you must install the [Unity Pipeline package](https://docs.unity.com/en-us/unity-cli/unity-pipeline/unity-pipeline-package) (version 0.9.0-exp.1 or later). Without it, the commands aren't compiled. Run them against an open Unity Editor as `unity command <group> <name> [arguments]`. `unity command --list` shows every command with its arguments.
6+
7+
## Typical workflow
8+
9+
```
10+
unity command netcode.gameobjects create_network_manager
11+
unity command netcode.gameobjects make_prefab --prefab Assets/Prefabs/Player.prefab
12+
unity command netcode.gameobjects.config set --field player_prefab --value Assets/Prefabs/Player.prefab
13+
unity command editor.playmode start
14+
unity command netcode.gameobjects.session start --mode Host
15+
unity command netcode.gameobjects.session wait_ready
16+
unity command netcode.gameobjects list_objects
17+
```
18+
19+
To test with several players, use [Multiplayer Play Mode](https://docs.unity3d.com/Packages/com.unity.multiplayer.playmode@latest) scenarios (`editor.playmode start_scenario`) and run the commands against each player's Editor with `unity command --project-path <player project path>`.
20+
21+
## Commands
22+
23+
### netcode.gameobjects
24+
25+
| **Command** | **Description** |
26+
| :--- | :--- |
27+
| `status` | Each NetworkManager: role (host, server, client), connection state, local client id, topology, session owner, client and object counts, ticks, transport address, and whether the session runs hybrid prefabs. |
28+
| `list_clients` | Connected clients with their player object, owned object count and round trip time. |
29+
| `list_objects` | Spawned NetworkObjects as this peer sees them, filtered by name or owner. |
30+
| `get_object` | One NetworkObject: owner, authority, ownership flags and who can change them, observers and NetworkBehaviours. |
31+
| `spawn` | Instantiate and spawn a registered network prefab at a position, optionally for an owner or as a player object. |
32+
| `despawn` | Despawn a NetworkObject, optionally keeping the GameObject. |
33+
| `change_owner` | Give a NetworkObject to another client, following the topology's ownership rules. |
34+
| `create_network_manager` | Add a NetworkManager with a UnityTransport to the active scene. |
35+
| `list_prefabs` | Network prefabs lists with their prefabs, and the lists and player prefab each NetworkManager uses. |
36+
| `register_prefab` | Add a network prefab to a network prefabs list and save the list. |
37+
| `make_prefab` | Add a NetworkObject to a prefab's root and report its prefab id hash. |
38+
| `audit` | Find setup problems that otherwise show when a session starts: in NetworkManagers (transport, topology, prefab lists, player prefab, hybrid prefab requirements) and in network prefabs (NetworkBehaviours without a NetworkObject, nested NetworkObjects, duplicate prefab ids, unregistered prefabs). `--scope config` or `--scope prefabs` runs one half. |
39+
40+
### netcode.gameobjects.profiler
41+
42+
| **Command** | **Description** |
43+
| :--- | :--- |
44+
| `get_stats` | Sample network traffic over a number of frames: bytes and messages sent and received, per message type. |
45+
46+
The total bytes sent and received are exact. Per message type, the bytes received can be overstated by up to 6 bytes per message, because Netcode for GameObjects reports received messages with their header's unpacked size.
47+
48+
### netcode.gameobjects.session
49+
50+
| **Command** | **Description** |
51+
| :--- | :--- |
52+
| `start` | Start the NetworkManager as host, server or client, optionally with another address and port. |
53+
| `stop` | Shut the NetworkManager down. |
54+
| `kick` | Disconnect a client from the server or host. |
55+
| `reconnect` | Disconnect a client and connect it again, then wait for it to be connected. A client that was already disconnected, for example kicked or timed out, just connects again. |
56+
| `wait_ready` | Wait until a client is connected, or a server has a number of clients. |
57+
58+
### netcode.gameobjects.simulator
59+
60+
The simulator applies packet delay, jitter and loss to UnityTransport through its simulator pipeline stage, which is available in the Editor and development builds. Settings last for the Editor session and also apply to sessions started later. Once the simulator, `timeout` and `lag_spike` are all off, the transport gets its own simulator settings back. While the simulator is on, the Console shows a warning in each play session it affects, and again when its settings change.
61+
62+
| **Command** | **Description** |
63+
| :--- | :--- |
64+
| `get` | The current simulated conditions. |
65+
| `set` | Set a preset and/or packet delay, jitter and loss. |
66+
| `list_presets` | Network condition presets. They come from the Multiplayer Tools package (2.0 or later). |
67+
| `lag_spike` | Drop every packet for a short time. |
68+
| `timeout` | Drop every packet until turned off, so connections time out. |
69+
70+
### netcode.gameobjects.config
71+
72+
| **Command** | **Description** |
73+
| :--- | :--- |
74+
| `get` | The NetworkManager's configuration and the names `set` accepts. |
75+
| `set` | Set a NetworkConfig field (for example `tick_rate`), the transport `address`, `port` or `listen_address`, the `player_prefab`, or the `log_level`. The log level also changes a running session. |
76+
77+
Commands that change scenes or assets are undoable where Unity supports it and don't save the scene; save it with `unity command scene save`. Commands that change a running session apply to the Editor they run in.
78+
79+
## Hybrid sessions
80+
81+
A session whose network prefabs include `GhostObject` prefabs runs on a Netcode for Entities world. Its traffic goes through Netcode for Entities on port 7979, not through the NetworkManager's UnityTransport. In a hybrid session:
82+
83+
- The `netcode.gameobjects.simulator` commands don't affect the session's traffic. `timeout` and `lag_spike` refuse to run.
84+
- The transport `address` and `port` set with `netcode.gameobjects.config set` or `netcode.gameobjects.session start` don't apply.
85+
- `get_stats` counts Netcode for GameObjects messages only, not `GhostObject` replication.
86+
87+
The commands say so in their notes when this applies. For the Netcode for Entities side of the session, use the Netcode for Entities commands, for example `netcode.simulator` and `netcode.profiler get_snapshot_stats`.
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
using System.Runtime.CompilerServices;
22

3+
// The Unity CLI commands (com.unity.pipeline) wrap the internal query layer in Editor/CliQueries.
4+
[assembly: InternalsVisibleTo("Unity.Netcode.GameObjects.CLI.Editor")]
5+
36
#if UNITY_INCLUDE_TESTS
47
#if UNITY_EDITOR
58
[assembly: InternalsVisibleTo("Unity.Netcode.GameObjects.Editor.Tests")]
9+
[assembly: InternalsVisibleTo("Unity.Netcode.GameObjects.CLI.Editor.Tests")]
610
[assembly: InternalsVisibleTo("TestProject.Runtime.Tests")]
711
#endif // UNITY_EDITOR
812
#endif // UNITY_INCLUDE_TESTS

‎com.unity.netcode.gameobjects/Editor/CLI.meta‎

Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
using System.Runtime.CompilerServices;
2+
3+
#if UNITY_INCLUDE_TESTS
4+
[assembly: InternalsVisibleTo("Unity.Netcode.GameObjects.CLI.Editor.Tests")]
5+
#endif // UNITY_INCLUDE_TESTS

‎com.unity.netcode.gameobjects/Editor/CLI/AssemblyInfo.cs.meta‎

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)