Skip to content

Commit d5c1f54

Browse files
committed
fix: clean up the CLI commands (MTT-15298)
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.
1 parent c5a64d1 commit d5c1f54

9 files changed

Lines changed: 285 additions & 100 deletions

File tree

‎com.unity.netcode.gameobjects/Documentation~/unity-cli-commands.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
Drive Netcode for GameObjects from the command line, a CI job or an AI agent with the Unity CLI. The commands 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.
44

5-
The commands are available when the project has the `com.unity.pipeline` package (version 0.9.0-exp.1 or later). Without it, nothing extra is compiled. Run them against an open Editor as `unity command <group> <name> [arguments]`; `unity command --list` shows every command with its arguments.
5+
The commands are available when the project has the `com.unity.pipeline` package (version 0.9.0-exp.1 or later). Without it, the commands aren't compiled. Run them against an open Editor as `unity command <group> <name> [arguments]`; `unity command --list` shows every command with its arguments.
66

77
## Typical workflow
88

@@ -55,13 +55,13 @@ To test with several players, use [Multiplayer Play Mode](https://docs.unity3d.c
5555

5656
### netcode.gameobjects.simulator
5757

58-
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.
58+
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.
5959

6060
| **Command** | **Description** |
6161
| :--- | :--- |
6262
| `get` | The current simulated conditions. |
6363
| `set` | Set a preset and/or packet delay, jitter and loss. |
64-
| `list_presets` | Network condition presets. They come from the Multiplayer Tools package. |
64+
| `list_presets` | Network condition presets. They come from the Multiplayer Tools package (2.0 or later). |
6565
| `lag_spike` | Drop every packet for a short time. |
6666
| `timeout` | Drop every packet until turned off, so connections time out. |
6767

‎com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliModels.cs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,8 @@ internal class SimulatorStatusResult
313313
{
314314
public SimulatorSettings Settings;
315315
public bool MultiplayerToolsInstalled;
316+
/// <summary>True when the installed Multiplayer Tools has the Network Simulator and its presets (2.0 or later).</summary>
317+
public bool NetworkSimulatorAvailable;
316318
public List<string> NetworkSimulatorComponents = new List<string>();
317319
public List<string> LiveTransports = new List<string>();
318320
public string AppliesWhen;

‎com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Authoring.cs‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,12 @@ internal static CreateNetworkManagerResult CreateNetworkManager(string name, Net
7272
manager.NetworkConfig ??= new NetworkConfig();
7373
manager.NetworkConfig.NetworkTransport = transport;
7474
manager.NetworkConfig.NetworkTopology = topology;
75-
transport.SetConnectionData(result.Address, (ushort)port);
75+
var listenAddress = DefaultListenAddress(result.Address);
76+
SetConnectionAddress(transport, result.Address, (ushort)port, listenAddress);
77+
if (!string.IsNullOrEmpty(listenAddress))
78+
{
79+
result.Notes.Add($"A server listens on every interface ({listenAddress}) so clients can reach it at {result.Address}. Change it with netcode.gameobjects.config set listen_address.");
80+
}
7681
EditorUtility.SetDirty(manager);
7782
EditorUtility.SetDirty(transport);
7883
EditorSceneManager.MarkSceneDirty(scene);
@@ -239,7 +244,7 @@ private static NetworkPrefabsList ResolveTargetList(string listPath, bool dryRun
239244
var defaultList = AssetDatabase.LoadAssetAtPath<NetworkPrefabsList>(defaultPath);
240245
if (defaultList == null)
241246
{
242-
notes.Add($"Created the default list at {defaultPath}. Attach it to your NetworkManager's Network Prefabs Lists (or let netcode.gameobjects create_network_manager do it).");
247+
notes.Add($"{(dryRun ? "Would create" : "Created")} the default list at {defaultPath}. Attach it to your NetworkManager's Network Prefabs Lists (or let netcode.gameobjects create_network_manager do it).");
243248
if (dryRun)
244249
{
245250
return null;

‎com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Config.cs‎

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ internal static ConfigSetResult SetConfig(string field, string value, string man
9393
{
9494
throw new ArgumentException($"{name} is a UnityTransport setting, and {manager.name} uses {manager.NetworkConfig.NetworkTransport?.GetType().Name ?? "no transport"}.");
9595
}
96+
RequireDirectConnection(utp, name);
9697
var data = utp.ConnectionData;
9798
target = utp;
9899
if (name == k_Port)
@@ -104,21 +105,21 @@ internal static ConfigSetResult SetConfig(string field, string value, string man
104105
}
105106
result.Previous = (int)data.Port;
106107
result.Value = (int)port;
107-
apply = () => utp.SetConnectionData(data.Address, port, data.ServerListenAddress);
108+
apply = () => SetConnectionAddress(utp, data.Address, port, data.ServerListenAddress);
108109
}
109110
else if (name == k_Address)
110111
{
111112
var address = RequireText(value, name);
112113
result.Previous = data.Address;
113114
result.Value = address;
114-
apply = () => utp.SetConnectionData(address, data.Port, data.ServerListenAddress);
115+
apply = () => SetConnectionAddress(utp, address, data.Port, data.ServerListenAddress);
115116
}
116117
else
117118
{
118119
var listen = string.IsNullOrWhiteSpace(value) ? null : value.Trim();
119120
result.Previous = data.ServerListenAddress;
120121
result.Value = listen;
121-
apply = () => utp.SetConnectionData(data.Address, data.Port, listen);
122+
apply = () => SetConnectionAddress(utp, data.Address, data.Port, listen);
122123
}
123124
break;
124125
}
@@ -152,7 +153,7 @@ internal static ConfigSetResult SetConfig(string field, string value, string man
152153
{
153154
var configField = SettableConfigFields().FirstOrDefault(f => ToSnakeCase(f.Name) == name) ?? throw new ArgumentException($"Unknown field '{field}'. Settable: {string.Join(", ", GetConfig(managerFilter).SettableFields)}.");
154155
var parsed = ParseValue(configField.FieldType, value, name);
155-
ValidateConfigValue(name, parsed, result.Notes);
156+
ValidateConfigValue(configField.Name, name, parsed, result.Notes);
156157
target = manager;
157158
var previous = configField.GetValue(manager.NetworkConfig);
158159
result.Previous = previous is Enum ? previous.ToString() : previous;
@@ -180,19 +181,19 @@ internal static ConfigSetResult SetConfig(string field, string value, string man
180181
return result;
181182
}
182183

183-
private static void ValidateConfigValue(string name, object value, List<string> notes)
184+
private static void ValidateConfigValue(string fieldName, string name, object value, List<string> notes)
184185
{
185-
switch (name)
186+
switch (fieldName)
186187
{
187-
case "tick_rate" when (uint)value == 0 || (uint)value > 1000:
188+
case nameof(NetworkConfig.TickRate) when (uint)value == 0 || (uint)value > 1000:
188189
throw new ArgumentException("tick_rate must be between 1 and 1000.");
189-
case "tick_rate" when (uint)value > 120:
190+
case nameof(NetworkConfig.TickRate) when (uint)value > 120:
190191
notes.Add("Tick rates above 120 cost a lot of bandwidth and CPU; 30 to 60 is typical.");
191192
break;
192-
case "network_topology" when (NetworkTopologyTypes)value == NetworkTopologyTypes.DistributedAuthority:
193+
case nameof(NetworkConfig.NetworkTopology) when (NetworkTopologyTypes)value == NetworkTopologyTypes.DistributedAuthority:
193194
notes.Add("Distributed authority needs a session service (use_cmb_service, e.g. through the Multiplayer Services SDK) or a distributed authority host.");
194195
break;
195-
case "client_connection_buffer_timeout" or "load_scene_timeout" or "time_resync_interval" when (int)value < 1:
196+
case nameof(NetworkConfig.ClientConnectionBufferTimeout) or nameof(NetworkConfig.LoadSceneTimeOut) or nameof(NetworkConfig.TimeResyncInterval) when (int)value < 1:
196197
throw new ArgumentException($"{name} must be at least 1.");
197198
}
198199
}
@@ -218,14 +219,15 @@ void Add(string severity, string code, string asset, string message)
218219
result.Issues.Add(new AuditIssue { Severity = severity, Code = code, Asset = asset, Message = message });
219220
}
220221

221-
var managers = string.IsNullOrWhiteSpace(managerFilter) ? FindManagers() : new List<NetworkManager> { ResolveManager(managerFilter) };
222+
var all = FindManagers();
223+
var managers = string.IsNullOrWhiteSpace(managerFilter) ? all : new List<NetworkManager> { ResolveManager(managerFilter, all) };
222224
if (managers.Count == 0)
223225
{
224226
throw new InvalidOperationException(NoManagerMessage);
225227
}
226-
if (FindManagers().Count > 1)
228+
if (all.Count > 1)
227229
{
228-
Add("warning", "SEVERAL_NETWORKMANAGERS", null, $"{FindManagers().Count} NetworkManagers in the open scenes. Only one becomes NetworkManager.Singleton; keep one per session.");
230+
Add("warning", "SEVERAL_NETWORKMANAGERS", null, $"{all.Count} NetworkManagers in the open scenes. Only one becomes NetworkManager.Singleton; keep one per session.");
229231
}
230232

231233
foreach (var manager in managers)

‎com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Session.cs‎

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,9 @@ internal static SessionResult Start(SessionMode mode, string managerFilter, stri
4949
{
5050
throw new ArgumentException("address and port can only be set on a UnityTransport. Configure your transport directly.");
5151
}
52+
RequireDirectConnection(utp, "address and port");
5253
var data = utp.ConnectionData;
53-
utp.SetConnectionData(string.IsNullOrWhiteSpace(address) ? data.Address : address.Trim(), port > 0 ? (ushort)port : data.Port, data.ServerListenAddress);
54+
SetConnectionAddress(utp, string.IsNullOrWhiteSpace(address) ? data.Address : address.Trim(), port > 0 ? (ushort)port : data.Port, data.ServerListenAddress);
5455
result.Notes.Add($"Transport set to {utp.ConnectionData.Address}:{utp.ConnectionData.Port} for this session.");
5556
}
5657

@@ -269,12 +270,12 @@ internal static SpawnResult Spawn(string prefab, float[] position, long owner, b
269270
}
270271

271272
var result = new SpawnResult { Manager = manager.name, Prefab = AssetDatabase.GetAssetPath(prefabAsset) };
272-
var ownerId = owner < 0 ? (manager.DistributedAuthorityMode ? manager.LocalClientId : NetworkManager.ServerClientId) : (ulong)owner;
273-
if (manager.DistributedAuthorityMode && ownerId != manager.LocalClientId)
273+
var ownerId = manager.DistributedAuthorityMode ? manager.LocalClientId : owner < 0 ? NetworkManager.ServerClientId : (ulong)owner;
274+
if (manager.DistributedAuthorityMode && owner >= 0 && (ulong)owner != manager.LocalClientId)
274275
{
275276
result.Notes.Add($"Distributed authority spawns are owned by the spawning client; owner {owner} is ignored. Transfer it afterwards with netcode.gameobjects change_owner.");
276277
}
277-
if (owner >= 0 && !manager.ConnectedClientsIds.Contains(ownerId))
278+
else if (owner >= 0 && !IsValidOwner(manager, ownerId))
278279
{
279280
throw new ArgumentException($"No connected client {owner}. List them with netcode.gameobjects list_clients.");
280281
}
@@ -334,7 +335,7 @@ internal static OwnershipChangeResult ChangeOwner(long networkObjectId, long new
334335
{
335336
throw new ArgumentException("owner must be a client id (0 or more). List them with netcode.gameobjects list_clients.");
336337
}
337-
if (!manager.ConnectedClientsIds.Contains((ulong)newOwner))
338+
if (!IsValidOwner(manager, (ulong)newOwner))
338339
{
339340
throw new ArgumentException($"No connected client {newOwner}. List them with netcode.gameobjects list_clients.");
340341
}
@@ -369,31 +370,33 @@ internal static OwnershipChangeResult ChangeOwner(long networkObjectId, long new
369370
networkObject.ChangeOwnership((ulong)newOwner);
370371
}
371372

372-
if (!manager.DistributedAuthorityMode && networkObject.OwnerClientId != (ulong)newOwner)
373+
// The change applies immediately when allowed; refusals are only logged at the Developer log level.
374+
if (networkObject.OwnerClientId != (ulong)newOwner)
373375
{
374-
throw new InvalidOperationException($"Ownership of {networkObject.name} didn't change{errors.Describe()}");
375-
}
376-
if (manager.DistributedAuthorityMode && errors.HasErrors)
377-
{
378-
throw new InvalidOperationException($"Ownership of {networkObject.name} didn't change{errors.Describe()} Check its ownership flags with netcode.gameobjects get_object.");
376+
throw new InvalidOperationException($"Ownership of {networkObject.name} didn't change{errors.Describe()}" + (manager.DistributedAuthorityMode
377+
? " It may be locked, need a request, not be transferable or be session-owner only; check its ownership flags with netcode.gameobjects get_object."
378+
: ""));
379379
}
380380
}
381381

382382
result.Owner = (long)networkObject.OwnerClientId;
383-
if (manager.DistributedAuthorityMode && networkObject.OwnerClientId != (ulong)newOwner)
384-
{
385-
result.Notes.Add("Distributed authority applies the change through the session; check it with netcode.gameobjects get_object.");
386-
}
387383
return result;
388384
}
389385

390386
// --- Helpers ---
391387

388+
/// <summary>A connected client, or with a client-server topology the server itself (a dedicated server isn't a client).</summary>
389+
private static bool IsValidOwner(NetworkManager manager, ulong clientId)
390+
{
391+
return manager.ConnectedClientsIds.Contains(clientId)
392+
|| (!manager.DistributedAuthorityMode && clientId == NetworkManager.ServerClientId);
393+
}
394+
392395
private static void ValidateTimeout(float timeoutSeconds)
393396
{
394397
if (timeoutSeconds <= 0 || timeoutSeconds > 600)
395398
{
396-
throw new ArgumentException("timeout must be between 1 and 600 seconds.");
399+
throw new ArgumentException("timeout must be more than 0 and at most 600 seconds.");
397400
}
398401
}
399402

0 commit comments

Comments
 (0)