Skip to content

fix: serialize Unity.Mathematics structs by their fields, not their swizzles - #1418

Merged
Scriptwonder merged 1 commit into
CoplayDev:betafrom
RizgarOzan:fix/unity-mathematics-serialization
Oct 2, 2026
Merged

Scriptwonder merged 1 commit into
CoplayDev:betafrom
RizgarOzan:fix/unity-mathematics-serialization

Conversation

@RizgarOzan

@RizgarOzan RizgarOzan commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Description

Reading mcpforunity://scene/gameobject/{id}/components on a component that holds a Unity.Mathematics struct (a SplineContainer with knots is the reported case, but any float3/quaternion field does it) never returns and the Editor main thread is stuck until Unity is killed (#1415).

GameObjectSerializer.GetComponentData hands every field and property to a Newtonsoft serializer that has converters for Vector3, Quaternion, Matrix4x4 and so on, but nothing for the math types. float3 exposes 117 public swizzle properties (xxy, zyx, …), float4 336, each returning a new struct with swizzles of its own, and ReferenceLoopHandling.Ignore does not prune value types, so the default object contract walks a combinatorial tree that in practice never finishes.

This adds a UnityMathematicsConverter that writes any value type from the Unity.Mathematics namespace as its public instance fields only: float3 → {x, y, z}, quaternion → {value: {x, y, z, w}}, float4x4 → its four float4 columns. Matching by namespace keeps the package free of a com.unity.mathematics dependency. Same class of bug as #585 and #1128, closed for the whole type family this time instead of per component.

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • Test update

Changes Made

  • MCPForUnity/Runtime/Serialization/UnityTypeConverters.cs: new UnityMathematicsConverter (CanConvert = value type in the Unity.Mathematics namespace, not primitive/enum; WriteJson emits the cached public instance fields through the serializer so nested math types go through the same path; CanRead = false).
  • MCPForUnity/Editor/Helpers/GameObjectSerializer.cs: registers it in _outputSerializerSettings next to Matrix4x4Converter.
  • TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/UnityMathematicsSerializationTests.cs: declares stand-in Unity.Mathematics.float2/float3/float4/quaternion structs with the same field + swizzle shape (the test project does not reference the real package; same approach as FusionUnsafeTypeSerializationTests) and checks that a component's float3, quaternion and List<float3> fields serialize as field-only objects, with unrelated fields untouched.

Compatibility / Package Source

  • Unity version(s) tested: 6000.3.9f1 (EditMode run below). Only System.Reflection and Newtonsoft APIs that exist on netstandard2.0 / 2021.3 are used.
  • Package source used: file:../../../MCPForUnity (the TestProjects manifest, unchanged)
  • Resolved commit hash: n/a (local package)

Testing/Screenshots/Recordings

  • Python tests — not touched
  • Unity EditMode tests
  • Unity PlayMode tests — n/a
  • Package import/compile check (as part of the EditMode run)

unity test TestProjects/UnityMCPTests --mode EditMode on 6000.3.9f1:

# converter registration removed, test kept
Failed  UnityMathematicsSerializationTests.GetComponentData_WritesMathematicsStructsAsTheirFieldsOnly
        (swizzle keys present in the float3 output)

# with the fix
Passed  UnityMathematicsSerializationTests (1/1), FusionUnsafeTypeSerializationTests (1/1),
        UIDocumentSerializationTests (5/5), Matrix4x4ConverterTests (7/7)
Full suite: 1245 tests, 1167 passed, 77 skipped, 1 failed

The one failure is ToolParamsTests.GetFloat_ValidFloat_ReturnsValue ("Expected: 2.5f But was: 25.0f"), the tr-TR culture bug that #1416 fixes; it fails on beta on this machine with or without this change.

Documentation Updates

  • I have added/removed/modified tools or resources — no, serialization behaviour only

Related Issues

Fixes #1415

Additional Notes

  • Not included: the per-component token budget suggested in the issue as a general safety net against the next runaway type. Happy to do that as a follow-up if you want it.
  • The new .cs.meta was generated by Unity 6000.3 (compact, guid-only form).
  • AI use: Claude Code wrote the converter, the test and this description at my request; the test runs above are from real runs on my machine.

Summary by CodeRabbit

  • New Features
    • Unity Mathematics values now serialize as JSON objects containing their public fields, including when nested in lists.
    • Swizzle properties are excluded from serialized output.

…wizzles

GetComponentData handed float3/quaternion values to Newtonsoft's default
object contract, which walks every public swizzle property (117 on float3,
336 on float4) and never finishes, so reading a SplineContainer's components
hung the Editor. A namespace-matched converter writes only the public fields.

Fixes CoplayDev#1415
@coderabbitai

coderabbitai Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: bd7beb73-ed3b-407d-8e17-97d4183ade8a

📥 Commits

Reviewing files that changed from the base of the PR and between ba8a975 and a9670cf.

📒 Files selected for processing (4)
  • MCPForUnity/Editor/Helpers/GameObjectSerializer.cs
  • MCPForUnity/Runtime/Serialization/UnityTypeConverters.cs
  • TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/UnityMathematicsSerializationTests.cs
  • TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/UnityMathematicsSerializationTests.cs.meta

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.


📝 Walkthrough

Walkthrough

The output serializer now uses UnityMathematicsConverter for Unity Mathematics value types. The converter writes public instance fields recursively and does not support reading. An edit mode test checks serialization of math structs and lists.

Changes

Unity Mathematics serialization

Layer / File(s) Summary
Field-based converter
MCPForUnity/Runtime/Serialization/UnityTypeConverters.cs
Adds a converter for non-primitive, non-enum value types in the Unity.Mathematics namespace. It serializes public instance fields recursively, caches reflected fields under a lock, and disables reading.
Output serializer integration and test
MCPForUnity/Editor/Helpers/GameObjectSerializer.cs, TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/UnityMathematicsSerializationTests.cs, TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/UnityMathematicsSerializationTests.cs.meta
Registers the converter in the output serializer. The edit mode test checks fields on float3 and quaternion, list element serialization, exclusion of swizzle properties, and preservation of an unrelated label.

Priority: ⬆️ High

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix · Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to a9670

This change makes component data for Unity Mathematics types serialize through their fields instead of their swizzle properties, which addresses the reported hangs. No merge-blocking issue was found.

Security Architecture Review

Security architecture risk: 🔵 Low · up to a9670

The change is confined to how existing component reads encode math values and avoids recursively expanding swizzle properties. No new privilege or component-write path was demonstrated. Coverage of additional math types and concurrent use remains limited.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The demonstrated changed exposure is the representation of matching math values reached through existing component-data reads. The registration changes serialization behavior, not the GetComponentData signature or caller authority. Full production caller reachability and transport authentication were not established by the supplied relationship evidence.

Trust Boundaries and Controls

  • observed — Namespace matching is a formatting selector, not proof of trusted assembly provenance. Any eligible struct in the exact namespace matches, but this converter only reflects public instance fields and does not itself grant identity, permission, or deserialization authority.

Resilience and Maintainability Implications

  • observed — The new reflection cache locks lookup and publication, and serialization proceeds outside that lock without writing component fields. Failed output conversion is discarded by the component-data wrapper. End-to-end concurrency safety remains unproven because the existing shared serializer and surrounding metadata cache have no synchronization visible in the inspected code; the changed range does not introduce those shared objects.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 8 functions across 3 files. (1 skipped: 1 … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: serializing Unity.Mathematics structs by their fields instead of recursively traversing swizzle properties.
Description check ✅ Passed The description is complete and follows the repository template. It explains the bug, implementation, compatibility, tests, known unrelated failure, documentation status, related issue, and additional…
Linked Issues check ✅ Passed The changes satisfy the coding objective in [#1415]. UnityMathematicsConverter matches non-primitive, non-enum value types in Unity.Mathematics without a package dependency. It writes public insta…
Out of Scope Changes check ✅ Passed The changes stay within [#1415]. The converter, serializer registration, and stand-in based EditMode test all support serialization of Unity.Mathematics structs and prevention of swizzle traversal. …
Full details: Docstring Coverage

Explanation

Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 8 functions across 3 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Scriptwonder
Scriptwonder merged commit 5eefb7a into CoplayDev:beta Oct 2, 2026
7 checks passed
toxifly added a commit to toxifly/unity-mcp that referenced this pull request Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: scene/gameobject/{id}/components hangs the Editor forever on components holding Unity.Mathematics structs (e.g. SplineContainer knots)

2 participants