Skip to content

fix(execute_code): alias Object and Random to UnityEngine; hint at Roslyn when CodeDom fails - #1455

Open
MohammediYunus wants to merge 1 commit into
CoplayDev:betafrom
MohammediYunus:fix/execute-code-object-random-alias
Open

MohammediYunus wants to merge 1 commit into
CoplayDev:betafrom
MohammediYunus:fix/execute-code-object-random-alias

Conversation

@MohammediYunus

@MohammediYunus MohammediYunus commented Oct 10, 2026 •

Copy link
Copy Markdown

Description

execute_code wraps every snippet in a class that imports both System and UnityEngine. That makes a bare Object or Random an ambiguous reference (CS0104), so everyday snippets like Object.DestroyImmediate(go), Object.FindObjectsByType<Camera>(...) and Random.Range(0, 10) fail to compile. It isn't only a CodeDom thing: Roslyn rejects them too, because the ambiguity comes from the wrapper's own using lines.

This adds two aliases to the wrapper:

using Object = UnityEngine.Object;
using Random = UnityEngine.Random;

The object keyword still means System.Object, and System.Random still works when you write it out. WrapperLineOffset goes from 10 to 12 so compile errors keep pointing at the user's own lines. Both the CodeDom and the Roslyn paths use that constant.

For the second half of #1439, a failed CodeDom compile now includes a hint in the error data. I didn't say "C# 6" in the hint because Unity's mcs actually accepts C# 7 tuples and is int n patterns. The clear failures start at C# 8 (switch expressions, ??=, is not), so the hint names those. It points at the Roslyn row in the Dependencies section of the MCP for Unity window, which is where the installer lives now. If compiler='codedom' was forced while Roslyn is already installed, it suggests compiler='auto' instead.

Aliasing Random goes a step past what the issue asked for. It's the same CS0104 problem, so I included it, but I'm happy to drop it and keep this to Object only if you'd prefer.

Before and after

Same snippet, compiler="auto" with no Roslyn installed (so CodeDom):

var go = new GameObject("mcp-probe");
Object.DestroyImmediate(go);
return go == null;

Before (beta 142ea0a):

"errors": [
  "Line 2: `Object' is an ambiguous reference between `object' and `UnityEngine.Object'",
  "Line 2: `object' does not contain a definition for `DestroyImmediate'"
],
"compiler": "codedom"

After: success: true, result: true.

Real execute_code responses in Unity 6000.3.24f1, before and after, with each backend ("Roslyn" means the Roslyn DLLs were in Assets/Plugins/Roslyn and compiler="auto"):

Snippet CodeDom before CodeDom after Roslyn before Roslyn after
Object.DestroyImmediate(go) CS0104 ok CS0104 ok
Object.FindObjectsByType<Camera>(...) CS0104 ok CS0104 ok
Random.Range(0, 1) CS0104 ok CS0104 ok
new System.Random(1).Next(1) ok ok ok ok
object o = 1; return o is int; ok ok ok ok
type error on user line 3 "Line 3" "Line 3" + hint "Line 3" "Line 3"
switch expression parse errors parse errors + hint ok ok

Example hint, CodeDom forced while Roslyn is installed:

Compiled with the legacy CodeDom compiler, which does not support C# 8+ syntax (switch expressions, ??=, 'is not'). Roslyn is installed, so retry with compiler='auto'.

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update
  • Refactoring (no functional changes)
  • Test update

Changes Made

  • ExecuteCode.cs: two alias lines in WrapUserCode, WrapperLineOffset 10 to 12 with a note that it must match the header length, and a hint field on the two CodeDom failure returns (forced codedom and the auto fallback). The Roslyn paths and the roslyn-not-available message are unchanged.
  • ExecuteCodeTests.cs: each case runs with codedom and with auto:
    • bare Object.DestroyImmediate
    • bare Random.Range
    • object plus System.Random still compiling
    • a type error on user line 3 reported as "Line 3". It sits on line 3 because both backends clamp to at least line 1, so a line-1 error can't catch an offset that is too large.
    • a switch expression that fails under CodeDom and carries the hint, or compiles cleanly when auto picks Roslyn.
  • execute_code.py: one sentence in the tool description saying Object and Random resolve to the UnityEngine types. The reference page is regenerated, and both skill copies of tools-reference.md got the same edit.

Compatibility / Package Source

  • Unity version(s) tested: 6000.3.24f1 (macOS, Apple silicon)
  • Package source used: file: (the TestProjects/UnityMCPTests setup)
  • Resolved commit hash from Packages/packages-lock.json: n/a (file: package)

No behaviour change for code that already writes UnityEngine.Object or System.Random in full, or that uses the object keyword. A bare Object or Random couldn't compile before, so snippets that work today keep working. There's one edge case I found while testing: a project with its own class named Random or Object in the global namespace. A snippet that used that class by its bare name used to bind to it and now gets CS0576. global::Random still reaches it, and snippets that don't use the name aren't affected.

To get .NET's random number generator, write new System.Random(seed). A bare new Random(42) was CS0104 before and is CS0712 now (UnityEngine.Random is static), so it's a compile error either way.

The test code only uses APIs that exist back to 2021.3 (GameObject, Object.DestroyImmediate, Random.Range). I couldn't run the 2021.3, 2022.3, 6000.0 or 6000.4 editors locally, so the floor compile is down to compile-check.yml.

Testing/Screenshots/Recordings

  • Python tests (cd Server && uv run pytest tests/ -v)
  • Unity EditMode tests
  • Unity PlayMode tests
  • Package import/compile check
  • Not applicable (explain why in Additional Notes)

All on Unity 6000.3.24f1 in batchmode (-batchmode -nographics -runTests -testPlatform EditMode):

  • ExecuteCodeTests on beta with only the new tests added: 36 passed, 6 failed (the alias and hint cases). The line-3 test passes on beta too, since 10 is right for the old header.
  • ExecuteCodeTests with this change: 42/42 under CodeDom, and 42/42 again with Roslyn in Assets/Plugins/Roslyn, so auto uses Roslyn.
  • With the offset put back to 10 on top of the new header, Execute_CompilationError_ReportsUserLineNumber fails for both cases ("Line 5" instead of "Line 3").
  • Full EditMode suite: 1572 tests, 1494 passed, 78 ignored, 0 failed.

Server side:

  • uv run pytest tests/ -v: 1575 passed, 18 skipped.
  • uv run python -m pytest tools/tests/: 205 passed.
  • tools/generate_docs_reference.py --check: up to date.
  • tools/check-unity-versions.sh: ran, but all four matrix versions were skipped because none of them are installed here.

Documentation Updates

  • I have added/removed/modified tools or resources
  • If yes, I have updated all documentation files using:
    • The LLM prompt at tools/UPDATE_DOCS_PROMPT.md (recommended)
    • Manual review of the generated changes

Only the description changed. I regenerated the reference page with tools/generate_docs_reference.py and made the same one-phrase edit in both skill copies.

Related Issues

Fixes #1439

Additional Notes

I left the roslyn-not-available message alone and kept the offset as a constant, so the change stays small and the new line-number test guards it.

Summary by CodeRabbit

  • Bug Fixes

    • Unqualified Object and Random in C# code execution now resolve to their Unity types; use System.Random to access .NET’s random number generator.
    • Compilation errors now report the corresponding line in your source code.
  • Improvements

    • CodeDom compilation failures now provide guidance, including when to retry with automatic compiler selection, install Roslyn, or use older C# syntax.
  • Documentation

    • Updated scripting references to explain type resolution and compiler failure guidance.

The execute_code wrapper imports both System and UnityEngine, so a bare
Object or Random was an ambiguous reference (CS0104) under both CodeDom
and Roslyn. Snippets like Object.DestroyImmediate(go) or
Random.Range(0, 10) never compiled.

- Add `using Object = UnityEngine.Object;` and
  `using Random = UnityEngine.Random;` to the wrapper. The `object`
  keyword still means System.Object, and System.Random still works when
  written out.
- Bump WrapperLineOffset from 10 to 12 so compiler errors keep pointing
  at the user's own lines (used by both the CodeDom and Roslyn paths).
- When a CodeDom compile fails, add a `hint` to the error data: point at
  the Roslyn row in the MCP for Unity window, or suggest compiler='auto'
  when codedom was forced and Roslyn is already installed.
- Document the aliases in the tool description, the generated reference
  page and both skill copies.
@coderabbitai

coderabbitai Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: eb18e478-8b28-4be2-9a78-f55d241ebbfc

📥 Commits

Reviewing files that changed from the base of the PR and between 142ea0a and 4213ce7.


📒 Files selected for processing (6)
  • .claude/skills/unity-mcp-skill/references/tools-reference.md
  • MCPForUnity/Editor/Tools/ExecuteCode.cs
  • Server/src/services/tools/execute_code.py
  • TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ExecuteCodeTests.cs
  • unity-mcp-skill/references/tools-reference.md
  • website/docs/reference/tools/scripting_ext/execute_code.md

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 execute_code wrapper now resolves unqualified Object and Random to UnityEngine types. CodeDom compilation failures include compiler guidance, and tests check type resolution, source-line reporting, and compiler behavior. Tool descriptions document the type names.

Changes

execute_code wrapper and compiler feedback

Layer / File(s) Summary
Wrapper type resolution
MCPForUnity/Editor/Tools/ExecuteCode.cs, TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ExecuteCodeTests.cs, .claude/skills/unity-mcp-skill/references/tools-reference.md, unity-mcp-skill/references/tools-reference.md, Server/src/services/tools/execute_code.py, website/docs/reference/tools/scripting_ext/execute_code.md
The generated wrapper aliases Object and Random to UnityEngine types. Tests check these aliases and confirm object and System.Random still compile. Tool descriptions explain the type resolution.
Compiler failure guidance and line reporting
MCPForUnity/Editor/Tools/ExecuteCode.cs, TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ExecuteCodeTests.cs
CodeDom compilation failures include guidance based on the selected compiler and Roslyn availability. The wrapper line offset changes, and tests check reported source lines and compiler-specific outcomes.

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: scriptwonder


Merge Risk: ⚪ Minimal · up to 4213c

The alias and compiler-guidance changes appear ready to merge after normal checks.

Pre-merge checks | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 18.18% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 3 files. (3 skipped: … 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 summarizes the two primary changes: UnityEngine aliases for Object and Random, and Roslyn guidance when CodeDom compilation fails.
Description check Passed The description follows the repository template and provides complete change details, compatibility information, testing results, documentation updates, and the related issue.
Linked Issues check Passed Direct issue [#1439] requires a UnityEngine.Object alias and a CodeDom failure hint. ExecuteCode.cs adds the wrapper aliases, sets WrapperLineOffset to 12, and returns hints for forced CodeDom and aut…
Out of Scope Changes check Passed The changes remain connected to [#1439]. The Random alias addresses the same System and UnityEngine name collision in the same execute_code wrapper. The line-offset update, regression tests, tool desc…

Full details: Docstring Coverage

Explanation

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


  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

This branch has not been deployed

No deployments
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.

[Feature]: CodeDom fallback — alias Object to UnityEngine.Object and hint to install Roslyn on compile failure

2 participants