diff --git a/com.unity.netcode.gameobjects/CHANGELOG.md b/com.unity.netcode.gameobjects/CHANGELOG.md
index 77e5e06762..e78da328f2 100644
--- a/com.unity.netcode.gameobjects/CHANGELOG.md
+++ b/com.unity.netcode.gameobjects/CHANGELOG.md
@@ -18,6 +18,7 @@ Additional documentation and release notes are available at [Multiplayer Documen
### Fixed
+- Ensured a useful and human readable error is logged when a NetworkVariable is trying to serialize a private or protected type. (#4239)
- Issue where `NetworkAnimator` logged an error for a trigger-conditioned transition into an Exit node, and a client that joined during that transition, or during one into a sub-state machine, did not synchronize with it. Transitions that pass through Exit, Entry or sub-state machine nodes now resolve to the state they reach, and a late-joining client cross-fades from the matching originating state when several states transition into the same destination. (#4238)
- Ensured all callbacks are wrapped with exception handling to avoid silent errors. (#4161)
diff --git a/com.unity.netcode.gameobjects/Documentation~/upgrade-guide.md b/com.unity.netcode.gameobjects/Documentation~/upgrade-guide.md
index 217a8c0c2e..8124d6c7bc 100644
--- a/com.unity.netcode.gameobjects/Documentation~/upgrade-guide.md
+++ b/com.unity.netcode.gameobjects/Documentation~/upgrade-guide.md
@@ -123,6 +123,14 @@ In version 2.x, the `Lerp` and `SmoothDampening` interpolation types smooth by d
Version 3.x introduces the foundations of the unified GameObject layer for Netcode for Entities, known as the hybrid prefab concept. Version 3.x doesn't enable this integration by default for standard GameObject workflows. Standard `NetworkBehaviour`, `NetworkVariable`, and RPC workflows work the same as in version 2.x.
+## CoreCLR compilation changes
+
+CoreCLR introduces a new compilation pipeline that changes some custom serialization generation.
+
+### NetworkVariable serialization
+
+The Mono compilation pipeline was capable of generating serialization for private and protected types. With CoreCLR, this is no longer possible and will fail the compilation. Ensure any types used inside NetworkVariables in your project are declared as `public` or `internal`.
+
## Additional resources
- [Install Netcode for GameObjects](install.md)
diff --git a/com.unity.netcode.gameobjects/Editor/CodeGen/CodeGenHelpers.cs b/com.unity.netcode.gameobjects/Editor/CodeGen/CodeGenHelpers.cs
index 41d4a8c570..626e6492b1 100644
--- a/com.unity.netcode.gameobjects/Editor/CodeGen/CodeGenHelpers.cs
+++ b/com.unity.netcode.gameobjects/Editor/CodeGen/CodeGenHelpers.cs
@@ -208,6 +208,61 @@ public static bool HasInterface(this TypeReference typeReference, string interfa
}
}
+ ///
+ /// Collects every type that assembly scoped code cannot access when it uses .
+ /// This is each private or protected nested type in its nesting chain, or in the chain of its generic arguments.
+ /// A protected internal type is only hidden when it is declared in an assembly whose internals cannot see.
+ ///
+ /// The type the generated code uses.
+ /// The assembly the generated code is emitted into.
+ /// Receives each inaccessible type, without duplicates.
+ public static void CollectTypesHiddenFromAssembly(this TypeReference type, AssemblyDefinition consumer, List hidden)
+ {
+ if (type is GenericInstanceType genericInstance)
+ {
+ foreach (var argument in genericInstance.GenericArguments)
+ {
+ argument.CollectTypesHiddenFromAssembly(consumer, hidden);
+ }
+ }
+ else if (type is TypeSpecification specification)
+ {
+ specification.ElementType.CollectTypesHiddenFromAssembly(consumer, hidden);
+ return;
+ }
+
+ for (var definition = type.Resolve(); definition != null && definition.IsNested; definition = definition.DeclaringType)
+ {
+ var isHidden = definition.IsNestedPrivate || definition.IsNestedFamily || definition.IsNestedFamilyAndAssembly ||
+ (definition.IsNestedFamilyOrAssembly && !consumer.CanSeeInternalsOf(definition.Module.Assembly));
+ if (isHidden && !hidden.Contains(definition))
+ {
+ hidden.Add(definition);
+ }
+ }
+ }
+
+ ///
+ /// Checks whether code in can access the internal members of .
+ ///
+ /// The assembly that accesses the members.
+ /// The assembly that declares the members.
+ /// True if both are the same assembly, or grants InternalsVisibleTo.
+ private static bool CanSeeInternalsOf(this AssemblyDefinition consumer, AssemblyDefinition owner)
+ {
+ if (owner.Name.Name == consumer.Name.Name)
+ {
+ return true;
+ }
+
+ // InternalsVisibleTo takes "Name" or "Name, PublicKey=..."; only the simple name matters here.
+ return owner.CustomAttributes.Any(attribute =>
+ attribute.AttributeType.FullName == typeof(System.Runtime.CompilerServices.InternalsVisibleToAttribute).FullName &&
+ attribute.ConstructorArguments.Count == 1 &&
+ attribute.ConstructorArguments[0].Value is string friend &&
+ friend.Split(',')[0].Trim() == consumer.Name.Name);
+ }
+
///
/// Checks a generic method instantiation against the generic constraints of the method it instantiates.
/// Mono does not enforce these on the calls codegen emits, but CoreCLR does, and it rejects the entire
diff --git a/com.unity.netcode.gameobjects/Editor/CodeGen/NetworkBehaviourILPP.cs b/com.unity.netcode.gameobjects/Editor/CodeGen/NetworkBehaviourILPP.cs
index d8ab346df4..5c9c0bddbb 100644
--- a/com.unity.netcode.gameobjects/Editor/CodeGen/NetworkBehaviourILPP.cs
+++ b/com.unity.netcode.gameobjects/Editor/CodeGen/NetworkBehaviourILPP.cs
@@ -437,6 +437,28 @@ private void CreateNetworkVariableTypeInitializers(AssemblyDefinition assembly,
continue;
}
+ // CoreCLR enforces member access on the generic calls emitted below; Mono does not.
+ var hiddenTypes = new List();
+ type.CollectTypesHiddenFromAssembly(assembly, hiddenTypes);
+ if (hiddenTypes.Count > 0)
+ {
+ // Use the target assembly's defines: a Mono editor can build a CoreCLR player.
+ if (assemblyDefines.Contains("ENABLE_CORECLR"))
+ {
+ foreach (var hiddenType in hiddenTypes)
+ {
+ m_Diagnostics.AddError($"{type} cannot be used in a network variable - Cannot access the {hiddenType.Name} type to generate serialization as it is {(hiddenType.IsNestedPrivate ? "private" : "protected")}. To fix this, change the access modifier to internal or public.");
+ }
+ continue;
+ }
+
+ // Log a warning in Mono so we can warn users who haven't yet switched their projects over.
+ foreach (var hiddenType in hiddenTypes)
+ {
+ m_Diagnostics.AddWarning($"NetworkVariable serialization for {type.Name} will fail in CoreCLR! With CoreCLR generated code cannot access the {hiddenType.Name} type to generate serialization as it is {(hiddenType.IsNestedPrivate ? "private" : "protected")}. To fix this, change the access modifier to internal or public.");
+ }
+ }
+
if (serializeMethod != null)
{
instructions.Add(processor.Create(OpCodes.Call, m_MainModule.ImportReference(serializeMethod)));