diff --git a/com.unity.netcode.gameobjects/CHANGELOG.md b/com.unity.netcode.gameobjects/CHANGELOG.md index d4792c13d7..58bd7d213a 100644 --- a/com.unity.netcode.gameobjects/CHANGELOG.md +++ b/com.unity.netcode.gameobjects/CHANGELOG.md @@ -10,6 +10,8 @@ Additional documentation and release notes are available at [Multiplayer Documen ### Added +- `netcode.gameobjects get_object` returns each NetworkBehaviour's `NetworkVariable` and `NetworkList` values as the peer sees them, and the child path of nested behaviours. `--behaviour` limits the values to one behaviour type, and `--variables false` gives the previous short form. (#4258) +- `netcode.gameobjects audit` checks in-scene NetworkObjects for a missing network id (`GlobalObjectIdHash` 0), and takes `--scope scenes` to run only that check. (#4258) - ILPP diagnostic errors should now be clickable in the editor to go to the source of the issue. (#4250) ### Changed @@ -22,6 +24,7 @@ Additional documentation and release notes are available at [Multiplayer Documen ### Fixed +- Issue where a `NetworkObject` added to a scene before the scene was first saved, for example by an editor script, was saved with a `GlobalObjectIdHash` of 0 and never spawned. Saving the scene now assigns the missing id and saves it again. (#4258) - Issue where every `NetworkObject` that started before a session logged a "Did not register because there is no session in progress!" warning when `NetworkManager.LogLevel` was `Developer`. Only `GhostObject` instances log it now. (#4245) - Fixed a NullReferenceException that would be thrown if a MonoBehaviour derived from NetworkManager defines it's own Awake or OnEnable. (#4244) - Issue where the unified bootstrap created a second world that ran a duplicate of every default system next to the default world. (#4243) diff --git a/com.unity.netcode.gameobjects/Documentation~/unity-cli-commands.md b/com.unity.netcode.gameobjects/Documentation~/unity-cli-commands.md index 313a55b689..42d4916f46 100644 --- a/com.unity.netcode.gameobjects/Documentation~/unity-cli-commands.md +++ b/com.unity.netcode.gameobjects/Documentation~/unity-cli-commands.md @@ -27,7 +27,7 @@ To test with several players, use [Multiplayer Play Mode](https://docs.unity3d.c | `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. | | `list_clients` | Connected clients with their player object, owned object count and round trip time. | | `list_objects` | Spawned NetworkObjects as this peer sees them, filtered by name or owner. | -| `get_object` | One NetworkObject: owner, authority, ownership flags and who can change them, observers and NetworkBehaviours. | +| `get_object` | One NetworkObject: owner, authority, ownership flags and who can change them, observers, NetworkBehaviours (nested ones with their child path), and each behaviour's `NetworkVariable` and `NetworkList` values as this peer sees them. `--behaviour` limits the values to one behaviour type; `--variables false` leaves them out. | | `spawn` | Instantiate and spawn a registered network prefab at a position, optionally for an owner or as a player object. | | `despawn` | Despawn a NetworkObject, optionally keeping the GameObject. | | `change_owner` | Give a NetworkObject to another client, following the topology's ownership rules. | @@ -35,7 +35,7 @@ To test with several players, use [Multiplayer Play Mode](https://docs.unity3d.c | `list_prefabs` | Network prefabs lists with their prefabs, and the lists and player prefab each NetworkManager uses. | | `register_prefab` | Add a network prefab to a network prefabs list and save the list. | | `make_prefab` | Add a NetworkObject to a prefab's root and report its prefab id hash. | -| `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. | +| `audit` | Find setup problems that otherwise show when a session starts: in NetworkManagers (transport, topology, prefab lists, player prefab, hybrid prefab requirements), in in-scene NetworkObjects (no network id, so they never spawn), and in network prefabs (NetworkBehaviours without a NetworkObject, nested NetworkObjects, duplicate prefab ids, unregistered prefabs). `--scope config`, `--scope scenes` or `--scope prefabs` runs one part. | ### netcode.gameobjects.profiler diff --git a/com.unity.netcode.gameobjects/Editor/CLI/NetcodeGameObjectsCliCommands.cs b/com.unity.netcode.gameobjects/Editor/CLI/NetcodeGameObjectsCliCommands.cs index f1d21cc285..8cf23dc982 100644 --- a/com.unity.netcode.gameobjects/Editor/CLI/NetcodeGameObjectsCliCommands.cs +++ b/com.unity.netcode.gameobjects/Editor/CLI/NetcodeGameObjectsCliCommands.cs @@ -33,11 +33,13 @@ private static object ListObjects( [CliArg("manager", "NetworkManager name or hierarchy path, when there are several.")] string manager = null) => NgoCliOutput.ToWire(NgoCliQueries.ListObjects(manager, nameContains, owner, limit)); - [CliGroupCommand(k_Group, "One spawned NetworkObject: owner, authority, ownership flags and who may change them, observers, NetworkBehaviours, scene and position. Requires a running session.", Tags = new[] { Tag })] + [CliGroupCommand(k_Group, "One spawned NetworkObject: owner, authority, ownership flags and who may change them, observers, NetworkBehaviours (nested ones with their child path), scene, position, and each behaviour's NetworkVariable and NetworkList values as this peer sees them. Requires a running session.", Tags = new[] { Tag })] private static object GetObject( [CliArg("id", "NetworkObjectId, from netcode.gameobjects list_objects.", Required = true)] long id, - [CliArg("manager", "NetworkManager name or hierarchy path, when there are several.")] string manager = null) - => NgoCliOutput.ToWire(NgoCliQueries.GetObject(id, manager)); + [CliArg("manager", "NetworkManager name or hierarchy path, when there are several.")] string manager = null, + [CliArg("behaviour", "Only this NetworkBehaviour's variables, by type name.")] string behaviour = null, + [CliArg("variables", "Include NetworkVariable values. False gives the short form.")] bool variables = true) + => NgoCliOutput.ToWire(NgoCliQueries.GetObject(id, manager, behaviour, variables)); [CliGroupCommand(k_Group, "Instantiate and spawn a registered network prefab. Server or host in client-server; any client in distributed authority (which then owns it). Returns the spawned object.", Tags = new[] { Tag })] private static object Spawn( @@ -89,9 +91,9 @@ private static object MakePrefab( [CliArg("dry-run", "Validate and report without changing the prefab.")] bool dryRun = false) => NgoCliOutput.ToWire(NgoCliQueries.MakePrefab(prefab, dryRun)); - [CliGroupCommand(k_Group, "Check the project for problems that otherwise show when a session starts: NetworkManager setups in the open scenes (transport, topology, prefab lists, player prefab, hierarchy, hybrid prefab requirements) and network prefabs (NetworkBehaviours without a NetworkObject, nested or misplaced NetworkObjects, NetworkManagers in network prefabs, missing or duplicate prefab ids, unregistered prefabs, broken list entries).", Tags = new[] { Tag })] + [CliGroupCommand(k_Group, "Check the project for problems that otherwise show when a session starts: NetworkManager setups in the open scenes (transport, topology, prefab lists, player prefab, hierarchy, hybrid prefab requirements), in-scene NetworkObjects without a network id, and network prefabs (NetworkBehaviours without a NetworkObject, nested or misplaced NetworkObjects, NetworkManagers in network prefabs, missing or duplicate prefab ids, unregistered prefabs, broken list entries).", Tags = new[] { Tag })] private static object Audit( - [CliArg("scope", "all, config (NetworkManagers) or prefabs.")] string scope = "all", + [CliArg("scope", "all, config (NetworkManagers), scenes (in-scene NetworkObjects) or prefabs.")] string scope = "all", [CliArg("folder", "Prefabs only: prefabs under this folder, e.g. Assets/Prefabs.")] string folder = null, [CliArg("limit", "Maximum issues returned (counts include all).")] int limit = 200, [CliArg("manager", "Config only: this NetworkManager (name or hierarchy path). Omit for all.")] string manager = null) diff --git a/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliModels.cs b/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliModels.cs index f20910dda2..74e12fde1b 100644 --- a/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliModels.cs +++ b/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliModels.cs @@ -109,6 +109,30 @@ internal class ObjectDetail : ObjectSummary public OwnershipInfo Ownership; public List Observers; public List Behaviours = new List(); + /// Each behaviour's NetworkVariable values as this peer sees them; null when variables weren't asked for. + public List State; + } + + internal class BehaviourState + { + public string Behaviour; + /// The behaviour's GameObject below the NetworkObject; null on the NetworkObject's own GameObject. + public string Path; + public List Variables = new List(); + } + + internal class VariableState + { + public string Name; + public string Type; + public object Value; + /// For a list or other collection: the full element count, though at most MaxElementsShown are shown. + public int? Count; + public bool Truncated; + public NetworkVariableReadPermission ReadPerm; + public NetworkVariableWritePermission WritePerm; + /// Why there's no value: not sent to this client, or the read failed. + public string Note; } internal class OwnershipInfo @@ -246,6 +270,8 @@ internal class ProjectAuditResult public int? ManagersChecked; /// Set when network prefabs were checked. public int? PrefabsScanned; + /// Set when the NetworkObjects in the open scenes were checked. + public int? SceneObjectsChecked; public int Errors; public int Warnings; public bool Truncated; @@ -257,7 +283,7 @@ internal class AuditIssue /// error or warning. public string Severity; public string Code; - /// config (NetworkManagers) or prefabs. + /// config (NetworkManagers), scenes (in-scene NetworkObjects) or prefabs. public string Area; public string Asset; public string Message; diff --git a/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Authoring.cs b/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Authoring.cs index 6d762de990..efe9d21a93 100644 --- a/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Authoring.cs +++ b/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Authoring.cs @@ -408,9 +408,9 @@ internal static MakePrefabResult MakePrefab(string prefab, bool dryRun) internal static ProjectAuditResult Audit(string scope, string folder, int limit, string managerFilter) { var normalized = string.IsNullOrWhiteSpace(scope) ? "all" : scope.Trim().ToLowerInvariant(); - if (normalized is not ("all" or "config" or "prefabs")) + if (normalized is not ("all" or "config" or "scenes" or "prefabs")) { - throw new ArgumentException("scope must be all, config or prefabs."); + throw new ArgumentException("scope must be all, config, scenes or prefabs."); } if (limit < 1) { @@ -419,7 +419,7 @@ internal static ProjectAuditResult Audit(string scope, string folder, int limit, var result = new ProjectAuditResult(); var issues = new List(); - if (normalized != "prefabs") + if (normalized is "all" or "config") { // A project check shouldn't fail because the scene with the NetworkManager isn't open. if (normalized == "all" && string.IsNullOrWhiteSpace(managerFilter) && FindManagers().Count == 0) @@ -441,7 +441,24 @@ internal static ProjectAuditResult Audit(string scope, string folder, int limit, } } } - if (normalized != "config") + if (normalized is "all" or "scenes") + { + var scenes = AuditScenes(); + result.SceneObjectsChecked = scenes.ObjectsChecked; + foreach (var issue in scenes.Issues) + { + if (issue.Severity == "error") + { + result.Errors++; + } + else + { + result.Warnings++; + } + issues.Add(issue); + } + } + if (normalized is "all" or "prefabs") { var prefabs = AuditPrefabs(folder, limit); result.PrefabsScanned = prefabs.PrefabsScanned; @@ -462,6 +479,58 @@ internal static ProjectAuditResult Audit(string scope, string folder, int limit, return result; } + /// + /// Checks the NetworkObjects placed in the open scenes for a missing network id (GlobalObjectIdHash 0). NGO + /// can't match such an object across peers, so it never spawns and a session that waits for it never starts. + /// It happens when a NetworkObject is added to a scene before the scene is first saved. + /// + internal static (int ObjectsChecked, List Issues) AuditScenes() + { + var issues = new List(); + var checkedCount = 0; + for (var i = 0; i < SceneManager.sceneCount; i++) + { + var scene = SceneManager.GetSceneAt(i); + if (!scene.isLoaded) + { + continue; + } + var unsaved = string.IsNullOrEmpty(scene.path); + var missing = new List(); + foreach (var networkObject in FindObjects.FromSceneByType(scene, true)) + { + checkedCount++; + if (networkObject.GlobalObjectIdHash == 0) + { + missing.Add(GetHierarchyPath(networkObject.transform)); + } + } + if (missing.Count == 0) + { + continue; + } + var names = string.Join(", ", missing.Count > 10 ? missing.GetRange(0, 10) : missing) + (missing.Count > 10 ? $" and {missing.Count - 10} more" : ""); + issues.Add(unsaved + ? new AuditIssue + { + Severity = "warning", + Code = "SCENE_NOT_SAVED", + Area = "scenes", + Asset = SceneLabel(scene), + Message = $"{missing.Count} NetworkObject(s) in a scene that has never been saved have no network id yet: {names}. Save the scene; NGO assigns the ids when it has a path.", + } + : new AuditIssue + { + Severity = "error", + Code = "IN_SCENE_ID_MISSING", + Area = "scenes", + Asset = scene.path, + Message = $"{missing.Count} in-scene NetworkObject(s) have no network id (GlobalObjectIdHash 0), so they never spawn: {names}. Save the scene to assign them (a scene saved by this NGO version gets them on save), or reopen it, mark it dirty and save.", + }); + } + return (checkedCount, issues); + } + /// /// Checks network prefabs for setup problems the editor otherwise reports one at a time, in the inspector or /// when a session starts: behaviours without a NetworkObject, nested or misplaced NetworkObjects, diff --git a/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Variables.cs b/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Variables.cs new file mode 100644 index 0000000000..0aca53a67c --- /dev/null +++ b/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Variables.cs @@ -0,0 +1,324 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.Reflection; +using UnityEngine; + +namespace Unity.Netcode.GameObjects.Editor.Cli +{ + internal static partial class NgoCliQueries + { + /// Most elements shown for a list or other collection value; the count is always the full one. + internal const int MaxElementsShown = 32; + + /// How deep struct and class values are expanded into their fields before falling back to ToString. + private const int k_MaxValueDepth = 2; + + private static readonly Dictionary s_ValueProperties = new Dictionary(); + + /// + /// The NetworkVariable values of each NetworkBehaviour a NetworkObject owns, as this peer sees them. Nested + /// behaviours carry the path of their GameObject below the NetworkObject. A variable that can't be read + /// reports why instead of failing the whole object. + /// + internal static List DescribeBehaviourState(NetworkManager manager, NetworkObject networkObject, string behaviourFilter) + { + var states = new List(); + foreach (var behaviour in OwnedBehaviours(networkObject)) + { + var type = behaviour.GetType(); + if (!string.IsNullOrEmpty(behaviourFilter) + && !string.Equals(type.Name, behaviourFilter, StringComparison.OrdinalIgnoreCase) + && !string.Equals(type.FullName, behaviourFilter, StringComparison.OrdinalIgnoreCase)) + { + continue; + } + var state = new BehaviourState + { + Behaviour = type.Name, + Path = RelativePath(networkObject.transform, behaviour.transform), + }; + foreach (var variable in behaviour.NetworkVariableFields) + { + state.Variables.Add(DescribeVariable(manager, variable)); + } + states.Add(state); + } + if (states.Count == 0 && !string.IsNullOrEmpty(behaviourFilter)) + { + throw new ArgumentException($"{networkObject.name} has no NetworkBehaviour named '{behaviourFilter}'. Its behaviours are listed under behaviours in netcode.gameobjects get_object."); + } + return states; + } + + /// The NetworkBehaviours NGO assigns to this NetworkObject: a nested NetworkObject owns the ones below it. + internal static IEnumerable OwnedBehaviours(NetworkObject networkObject) + { + foreach (var behaviour in networkObject.GetComponentsInChildren(true)) + { + if (behaviour.GetComponentInParent(true) == networkObject) + { + yield return behaviour; + } + } + } + + private static VariableState DescribeVariable(NetworkManager manager, NetworkVariableBase variable) + { + var state = new VariableState + { + Name = variable.Name, + Type = FriendlyTypeName(variable.GetType()), + ReadPerm = variable.ReadPerm, + WritePerm = variable.WritePerm, + }; + try + { + if (!manager.IsServer && !variable.CanClientRead(manager.LocalClientId)) + { + state.Note = $"Not sent to this client: read permission is {variable.ReadPerm}. Read it on the server or the owner."; + return state; + } + var valueProperty = GetValueProperty(variable.GetType()); + if (valueProperty != null) + { + state.Value = FormatTopLevel(valueProperty.GetValue(variable), state); + } + else if (variable is IEnumerable collection) + { + state.Value = FormatTopLevel(collection, state); + } + else if (GetEnumeratorMethod(variable.GetType()) is { } getEnumerator) + { + // NetworkList has a public GetEnumerator but doesn't implement IEnumerable. + state.Value = FormatTopLevel(new EnumeratorSource((IEnumerator)getEnumerator.Invoke(variable, null)), state); + } + else + { + state.Value = variable.ToString(); + } + } + catch (Exception exception) + { + var inner = exception is TargetInvocationException { InnerException: not null } ? exception.InnerException : exception; + state.Note = $"Couldn't read the value: {inner.GetType().Name}: {inner.Message}"; + } + return state; + } + + /// The public instance Value property of NetworkVariable<T>, AnticipatedNetworkVariable<T> and similar, cached per type. + private static PropertyInfo GetValueProperty(Type variableType) + { + if (!s_ValueProperties.TryGetValue(variableType, out var property)) + { + property = variableType.GetProperty("Value", BindingFlags.Instance | BindingFlags.Public); + if (property != null && (!property.CanRead || property.GetIndexParameters().Length > 0)) + { + property = null; + } + s_ValueProperties[variableType] = property; + } + return property; + } + + private static MethodInfo GetEnumeratorMethod(Type variableType) + { + var method = variableType.GetMethod("GetEnumerator", BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null); + return method != null && typeof(IEnumerator).IsAssignableFrom(method.ReturnType) ? method : null; + } + + /// Lets an enumerator from a duck-typed GetEnumerator be read as a collection. + private sealed class EnumeratorSource : IEnumerable + { + private readonly IEnumerator m_Enumerator; + + internal EnumeratorSource(IEnumerator enumerator) + { + m_Enumerator = enumerator; + } + + public IEnumerator GetEnumerator() => m_Enumerator; + } + + private static object FormatTopLevel(object value, VariableState state) + { + if (value is IEnumerable collection && !IsScalar(value)) + { + var items = new List(); + var count = 0; + foreach (var item in collection) + { + if (count < MaxElementsShown) + { + items.Add(FormatValue(item, 1)); + } + count++; + } + state.Count = count; + state.Truncated = count > MaxElementsShown; + return items; + } + return FormatValue(value, 0); + } + + /// + /// Turns a NetworkVariable value into plain data the CLI can return: numbers, strings and enum names as they + /// are, Unity vectors, quaternions and colours as arrays, references as their ids and names, collections as + /// capped lists, and other structs and classes as their public fields, a couple of levels deep. + /// + internal static object FormatValue(object value, int depth) + { + switch (value) + { + case null: + return null; + case string or bool or char: + return value; + case Enum e: + return e.ToString(); + case float f: + return f; + case double d: + return d; + case Vector2 v: + return new[] { v.x, v.y }; + case Vector3 v: + return new[] { v.x, v.y, v.z }; + case Vector4 v: + return new[] { v.x, v.y, v.z, v.w }; + case Vector2Int v: + return new[] { v.x, v.y }; + case Vector3Int v: + return new[] { v.x, v.y, v.z }; + case Quaternion q: + return new[] { q.x, q.y, q.z, q.w }; + case Color c: + return new[] { c.r, c.g, c.b, c.a }; + case Color32 c: + return new[] { (int)c.r, c.g, c.b, c.a }; + case NetworkObjectReference reference: + return DescribeReference(reference); + case NetworkBehaviourReference reference: + return reference.TryGet(out NetworkBehaviour referenced) + ? new Dictionary + { + ["networkObjectId"] = (long)referenced.NetworkObjectId, + ["behaviour"] = referenced.GetType().Name, + ["name"] = referenced.name, + } + : null; + case UnityEngine.Object unityObject: + // A destroyed object compares equal to null. + return unityObject ? unityObject.name : null; + } + + var type = value.GetType(); + if (type.IsPrimitive || value is decimal) + { + return value; + } + if (IsScalar(value)) + { + return value.ToString(); + } + if (value is IDictionary dictionary) + { + var result = new Dictionary(); + foreach (DictionaryEntry entry in dictionary) + { + if (result.Count == MaxElementsShown) + { + break; + } + result[Convert.ToString(entry.Key, CultureInfo.InvariantCulture)] = depth < k_MaxValueDepth ? FormatValue(entry.Value, depth + 1) : entry.Value?.ToString(); + } + return result; + } + if (value is IEnumerable enumerable) + { + var result = new List(); + foreach (var item in enumerable) + { + if (result.Count == MaxElementsShown) + { + break; + } + result.Add(depth < k_MaxValueDepth ? FormatValue(item, depth + 1) : item?.ToString()); + } + return result; + } + if (depth >= k_MaxValueDepth) + { + return value.ToString(); + } + var fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public); + if (fields.Length == 0) + { + return value.ToString(); + } + var members = new Dictionary(); + foreach (var field in fields) + { + members[field.Name] = FormatValue(field.GetValue(value), depth + 1); + } + return members; + } + + private static Dictionary DescribeReference(NetworkObjectReference reference) + { + var result = new Dictionary { ["networkObjectId"] = (long)reference.NetworkObjectId }; + if (reference.TryGet(out var referenced)) + { + result["name"] = referenced.name; + } + return result; + } + + /// Values best shown as their text: Unity.Collections fixed strings, and Guid-like types with no fields. + private static bool IsScalar(object value) + { + var type = value.GetType(); + return (type.Namespace == "Unity.Collections" && type.Name.StartsWith("FixedString", StringComparison.Ordinal)) + || value is Guid || value is DateTime || value is TimeSpan; + } + + /// NetworkVariable<Int32> rather than NetworkVariable`1. + private static string FriendlyTypeName(Type type) + { + if (!type.IsGenericType) + { + return type.Name; + } + var name = type.Name; + var tick = name.IndexOf('`'); + if (tick >= 0) + { + name = name.Substring(0, tick); + } + var arguments = type.GetGenericArguments(); + var names = new string[arguments.Length]; + for (var i = 0; i < arguments.Length; i++) + { + names[i] = FriendlyTypeName(arguments[i]); + } + return $"{name}<{string.Join(", ", names)}>"; + } + + /// The path of below , or null when they're the same. + private static string RelativePath(Transform root, Transform child) + { + if (child == root) + { + return null; + } + var parts = new List(); + for (var current = child; current != null && current != root; current = current.parent) + { + parts.Add(current.name); + } + parts.Reverse(); + return string.Join("/", parts); + } + } +} diff --git a/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Variables.cs.meta b/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Variables.cs.meta new file mode 100644 index 0000000000..91677bb3b0 --- /dev/null +++ b/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Variables.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 942305f4d28e412fadfb22044513d65d \ No newline at end of file diff --git a/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.cs b/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.cs index 39f85b656c..6f3c6e5679 100644 --- a/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.cs +++ b/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.cs @@ -293,11 +293,16 @@ internal static ObjectListResult ListObjects(string managerFilter, string nameCo return result; } - internal static ObjectDetail GetObject(long networkObjectId, string managerFilter) + internal static ObjectDetail GetObject(long networkObjectId, string managerFilter, string behaviourFilter = null, bool variables = true) { var manager = ResolveRunningManager(managerFilter); var networkObject = FindSpawnedObject(manager, networkObjectId); - return Describe(manager, networkObject); + var detail = Describe(manager, networkObject); + if (variables) + { + detail.State = DescribeBehaviourState(manager, networkObject, behaviourFilter); + } + return detail; } internal static ObjectDetail Describe(NetworkManager manager, NetworkObject networkObject) @@ -309,13 +314,9 @@ internal static ObjectDetail Describe(NetworkManager manager, NetworkObject netw detail.DestroyWithScene = networkObject.DestroyWithScene; detail.DontDestroyWithOwner = networkObject.DontDestroyWithOwner; detail.Ownership = DescribeOwnership(manager, networkObject); - foreach (var behaviour in networkObject.GetComponentsInChildren(true)) + foreach (var behaviour in OwnedBehaviours(networkObject)) { - // As NGO assigns them: a nested NetworkObject owns the behaviours below it. - if (behaviour.GetComponentInParent(true) == networkObject) - { - detail.Behaviours.Add(behaviour.GetType().Name); - } + detail.Behaviours.Add(behaviour.GetType().Name); } // Observers are only tracked by the authority that decides visibility. diff --git a/com.unity.netcode.gameobjects/Editor/InScenePlacedProcessor.cs b/com.unity.netcode.gameobjects/Editor/InScenePlacedProcessor.cs index 8c326e5107..89864dc1cc 100644 --- a/com.unity.netcode.gameobjects/Editor/InScenePlacedProcessor.cs +++ b/com.unity.netcode.gameobjects/Editor/InScenePlacedProcessor.cs @@ -82,6 +82,71 @@ public static void ReportSceneIssues(Scene scene, bool hasAwakeRun) } } + /// + /// Gives in-scene placed s the GlobalObjectIdHash they missed, when their scene is saved. + /// + /// + /// NetworkObject.OnValidate can only generate the hash once the scene has an asset path, and a later + /// revalidation of a plain scene object doesn't mark the scene dirty. So a NetworkObject added to a new scene + /// (by an editor script, for instance) and saved with it keeps a hash of 0, and never spawns. After each save, + /// this regenerates any hash that is still 0 and saves the scene again. + /// + [InitializeOnLoad] + internal static class InSceneNetworkObjectIdRepair + { + private static bool s_Saving; + + static InSceneNetworkObjectIdRepair() + { + UnityEditor.SceneManagement.EditorSceneManager.sceneSaved += OnSceneSaved; + } + + /// Regenerates the hash of each NetworkObject in the scene that has none; returns how many now have one. + internal static int Repair(Scene scene) + { + var repaired = 0; + if (!scene.IsValid() || !scene.isLoaded || string.IsNullOrEmpty(scene.path)) + { + return repaired; + } + foreach (var networkObject in FindObjects.FromSceneByType(scene, true)) + { + if (networkObject.GlobalObjectIdHash != 0) + { + continue; + } + networkObject.OnValidate(); + if (networkObject.GlobalObjectIdHash != 0) + { + repaired++; + } + } + return repaired; + } + + private static void OnSceneSaved(Scene scene) + { + if (s_Saving || EditorApplication.isPlayingOrWillChangePlaymode) + { + return; + } + if (Repair(scene) == 0) + { + return; + } + s_Saving = true; + try + { + UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(scene); + UnityEditor.SceneManagement.EditorSceneManager.SaveScene(scene); + } + finally + { + s_Saving = false; + } + } + } + /// /// An that sets the property to false for all s in prefabs. /// Ensures that InScenePlaced is always false for all prefab objects. diff --git a/com.unity.netcode.gameobjects/Tests/Editor/Cli/Commands/NetcodeGameObjectsCliCommandsTests.cs b/com.unity.netcode.gameobjects/Tests/Editor/Cli/Commands/NetcodeGameObjectsCliCommandsTests.cs index 488095d78d..bf5b31f006 100644 --- a/com.unity.netcode.gameobjects/Tests/Editor/Cli/Commands/NetcodeGameObjectsCliCommandsTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Editor/Cli/Commands/NetcodeGameObjectsCliCommandsTests.cs @@ -27,7 +27,7 @@ internal class NetcodeGameObjectsCliCommandsTests ["netcode.gameobjects status"] = new string[0], ["netcode.gameobjects list_clients"] = new[] { "manager" }, ["netcode.gameobjects list_objects"] = new[] { "name-contains", "owner", "limit", "manager" }, - ["netcode.gameobjects get_object"] = new[] { "id*", "manager" }, + ["netcode.gameobjects get_object"] = new[] { "id*", "manager", "behaviour", "variables" }, ["netcode.gameobjects spawn"] = new[] { "prefab*", "position", "owner", "player-object", "manager" }, ["netcode.gameobjects despawn"] = new[] { "id*", "destroy", "manager" }, ["netcode.gameobjects change_owner"] = new[] { "id*", "owner*", "manager" }, diff --git a/com.unity.netcode.gameobjects/Tests/Editor/Cli/NgoCliQueriesTests.cs b/com.unity.netcode.gameobjects/Tests/Editor/Cli/NgoCliQueriesTests.cs index b25b7d1c1c..6790cf272b 100644 --- a/com.unity.netcode.gameobjects/Tests/Editor/Cli/NgoCliQueriesTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Editor/Cli/NgoCliQueriesTests.cs @@ -7,6 +7,7 @@ using System.Text.RegularExpressions; using System.Threading.Tasks; using NUnit.Framework; +using Unity.Collections; using Unity.Netcode.GameObjects.Editor.Cli; using Unity.Netcode.GameObjects.Editor.Configuration; using Unity.Netcode.Transports.UTP; @@ -438,6 +439,45 @@ public void AuditPrefabs_FindsSetupProblems() Assert.Throws(() => NgoCliQueries.Audit("config", null, 50, null), "Asking for the NetworkManager checks needs one."); } + /// + /// A NetworkObject added to a scene before its first save has no network id. Saving gives it one (the save + /// hook regenerates it and saves again), and audit reports any in-scene object still without one. + /// + [Test] + public void InSceneNetworkObject_GetsItsIdOnSave_AndAuditReportsMissingIds() + { + var gameManager = new GameObject("GameManager", typeof(NetworkObject)); + var networkObject = gameManager.GetComponent(); + Assert.AreEqual(0u, networkObject.GlobalObjectIdHash, "A scene with no path can't give it an id yet."); + + var unsaved = NgoCliQueries.Audit("scenes", null, 50, null); + Assert.AreEqual(1, unsaved.SceneObjectsChecked); + Assert.AreEqual("SCENE_NOT_SAVED", Only(unsaved.Issues).Code); + Assert.IsNull(unsaved.ManagersChecked, "scope scenes skips the NetworkManager checks."); + + var scenePath = $"{k_Folder}/CliIdScene.unity"; + Assert.IsTrue(EditorSceneManager.SaveScene(gameManager.scene, scenePath)); + Assert.AreNotEqual(0u, networkObject.GlobalObjectIdHash, "Saving assigns the id."); + var assigned = networkObject.GlobalObjectIdHash; + + // The id has to be in the saved file, which is what clones and builds load. + EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single); + var reopened = Only(new List(FindObjects.FromSceneByType(UnityEngine.SceneManagement.SceneManager.GetActiveScene(), true))); + Assert.AreEqual(assigned, reopened.GlobalObjectIdHash); + Assert.IsEmpty(NgoCliQueries.Audit("scenes", null, 50, null).Issues); + + // A scene saved before this fix can still hold an object with no id. + reopened.GlobalObjectIdHash = 0; + var missing = Only(NgoCliQueries.Audit("scenes", null, 50, null).Issues); + Assert.AreEqual("IN_SCENE_ID_MISSING", missing.Code); + Assert.AreEqual("error", missing.Severity); + Assert.AreEqual(scenePath, missing.Asset); + StringAssert.Contains("GameManager", missing.Message); + + EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); + Assert.Throws(() => NgoCliQueries.Audit("everything", null, 50, null)); + } + // --- Config --- [Test] @@ -778,6 +818,143 @@ public IEnumerator RunningHost_SupportsTheRuntimeQueries() StringAssert.Contains("stopped as the server", stoppedServer.Message); } + internal enum CliTestPhase { Waiting, Playing } + + internal struct CliTestScore : INetworkSerializeByMemcpy + { + public int Points; + public FixedString32Bytes Label; + } + + internal class CliStateBehaviour : NetworkBehaviour + { + public NetworkVariable Counter = new NetworkVariable(); + public NetworkVariable Spot = new NetworkVariable(); + public NetworkVariable Phase = new NetworkVariable(); + public NetworkVariable Title = new NetworkVariable(); + public NetworkVariable Score = new NetworkVariable(); + public NetworkVariable Secret = new NetworkVariable(readPerm: NetworkVariableReadPermission.Owner); + public NetworkList Hits; + + private void Awake() + { + // NetworkList allocates native memory, so it's created here rather than in a field initializer. + Hits = new NetworkList(); + } + } + + internal class CliChildBehaviour : NetworkBehaviour + { + public NetworkVariable Lit = new NetworkVariable(); + } + + private static VariableState Variable(BehaviourState state, string name) + { + foreach (var variable in state.Variables) + { + if (variable.Name == name) + { + return variable; + } + } + Assert.Fail($"{state.Behaviour} has no variable {name}."); + return null; + } + + [Test] + public void FormatValue_TurnsValuesIntoPlainData() + { + Assert.AreEqual(5, NgoCliQueries.FormatValue(5, 0)); + Assert.AreEqual("Playing", NgoCliQueries.FormatValue(CliTestPhase.Playing, 0)); + CollectionAssert.AreEqual(new[] { 1f, 2f, 3f }, (float[])NgoCliQueries.FormatValue(new Vector3(1, 2, 3), 0)); + Assert.AreEqual("hello", NgoCliQueries.FormatValue(new FixedString32Bytes("hello"), 0)); + var score = (Dictionary)NgoCliQueries.FormatValue(new CliTestScore { Points = 7, Label = "red" }, 0); + Assert.AreEqual(7, score["Points"]); + Assert.AreEqual("red", score["Label"]); + var many = new List(); + for (var i = 0; i < NgoCliQueries.MaxElementsShown + 5; i++) + { + many.Add(i); + } + Assert.AreEqual(NgoCliQueries.MaxElementsShown, ((List)NgoCliQueries.FormatValue(many, 0)).Count, "Collections are capped."); + Assert.IsNull(NgoCliQueries.FormatValue(null, 0)); + } + + /// + /// get_object returns each owned behaviour's NetworkVariable values, nested behaviours with their child path, + /// and NetworkList contents, so they can be read without script eval. + /// + [UnityTest] + public IEnumerator RunningHost_GetObjectReturnsNetworkVariableValues() + { + UsePlayModeWithoutReload(); + var manager = CreateManager(port: GetFreeUdpPort()); + manager.NetworkConfig.EnableSceneManagement = false; + + yield return new EnterPlayMode(); + + NgoCliQueries.Start(NgoCliQueries.SessionMode.Host, null, null, -1); + var ready = NgoCliQueries.WaitReadyAsync(null, 0, 10); + yield return WaitFor(ready); + Assert.IsTrue(ready.Result.Ready, ready.Result.Reason); + + var root = new GameObject("CliStateObject"); + root.AddComponent(); + var state = root.AddComponent(); + var child = new GameObject("Lamp"); + child.transform.SetParent(root.transform); + var lamp = child.AddComponent(); + var networkObject = root.GetComponent(); + // Built at runtime, so it has no prefab id; the host is the only peer, so any id will do. + networkObject.GlobalObjectIdHash = 0x5EED; + networkObject.Spawn(); + + state.Counter.Value = 3; + state.Spot.Value = new Vector3(1, 2, 3); + state.Phase.Value = CliTestPhase.Playing; + state.Title.Value = "arena"; + state.Score.Value = new CliTestScore { Points = 7, Label = "red" }; + state.Secret.Value = 42; + state.Hits.Add(4); + state.Hits.Add(5); + lamp.Lit.Value = true; + + var id = (long)networkObject.NetworkObjectId; + var detail = NgoCliQueries.GetObject(id, null); + CollectionAssert.AreEqual(new[] { nameof(CliStateBehaviour), nameof(CliChildBehaviour) }, detail.Behaviours); + Assert.AreEqual(2, detail.State.Count); + + var rootState = detail.State[0]; + Assert.IsNull(rootState.Path, "Behaviours on the NetworkObject's own GameObject have no path."); + Assert.AreEqual(3, Variable(rootState, "Counter").Value); + Assert.AreEqual("NetworkVariable", Variable(rootState, "Counter").Type); + CollectionAssert.AreEqual(new[] { 1f, 2f, 3f }, (float[])Variable(rootState, "Spot").Value); + Assert.AreEqual("Playing", Variable(rootState, "Phase").Value); + Assert.AreEqual("arena", Variable(rootState, "Title").Value); + Assert.AreEqual(7, ((Dictionary)Variable(rootState, "Score").Value)["Points"]); + Assert.AreEqual(42, Variable(rootState, "Secret").Value, "The server reads owner-only variables."); + var hits = Variable(rootState, "Hits"); + CollectionAssert.AreEqual(new object[] { 4, 5 }, (List)hits.Value); + Assert.AreEqual(2, hits.Count); + Assert.IsFalse(hits.Truncated); + + var childState = detail.State[1]; + Assert.AreEqual("Lamp", childState.Path); + Assert.AreEqual(true, Variable(childState, "Lit").Value); + + var filtered = NgoCliQueries.GetObject(id, null, nameof(CliChildBehaviour)); + Assert.AreEqual(nameof(CliChildBehaviour), Only(filtered.State).Behaviour); + Assert.Throws(() => NgoCliQueries.GetObject(id, null, "NoSuchBehaviour")); + Assert.IsNull(NgoCliQueries.GetObject(id, null, null, false).State, "variables false gives the short form."); + + var wire = (Dictionary)NgoCliOutput.ToWire(detail); + Assert.IsTrue(wire.ContainsKey("state")); + + networkObject.Despawn(); + NgoCliQueries.Stop(null, false); + yield return WaitForCondition(() => !manager.IsListening && !manager.ShutdownInProgress); + } + /// /// Runs a host and a second NetworkManager as its client in the same play session, and drives the commands /// that act on a remote client: start with a transport override, ownership, kick, reconnect, and a stats