2025-12-30 01:30:45 +08:00
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Globalization;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Reflection;
|
|
|
|
|
using MCPForUnity.Editor.Constants;
|
|
|
|
|
using MCPForUnity.Editor.Helpers;
|
|
|
|
|
using UnityEditor;
|
|
|
|
|
using UnityEngine;
|
|
|
|
|
using UnityEngine.UIElements;
|
|
|
|
|
|
|
|
|
|
namespace MCPForUnity.Editor.Windows
|
|
|
|
|
{
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Editor window for managing Unity EditorPrefs, specifically for MCP For Unity development
|
|
|
|
|
/// </summary>
|
|
|
|
|
public class EditorPrefsWindow : EditorWindow
|
|
|
|
|
{
|
|
|
|
|
// UI Elements
|
|
|
|
|
private ScrollView scrollView;
|
|
|
|
|
private VisualElement prefsContainer;
|
|
|
|
|
|
|
|
|
|
// Data
|
|
|
|
|
private List<EditorPrefItem> currentPrefs = new List<EditorPrefItem>();
|
|
|
|
|
private HashSet<string> knownMcpKeys = new HashSet<string>();
|
|
|
|
|
|
|
|
|
|
// Type mapping for known EditorPrefs
|
|
|
|
|
private readonly Dictionary<string, EditorPrefType> knownPrefTypes = new Dictionary<string, EditorPrefType>
|
|
|
|
|
{
|
|
|
|
|
// Boolean prefs
|
|
|
|
|
{ EditorPrefKeys.DebugLogs, EditorPrefType.Bool },
|
|
|
|
|
{ EditorPrefKeys.UseHttpTransport, EditorPrefType.Bool },
|
|
|
|
|
{ EditorPrefKeys.ResumeHttpAfterReload, EditorPrefType.Bool },
|
|
|
|
|
{ EditorPrefKeys.ResumeStdioAfterReload, EditorPrefType.Bool },
|
|
|
|
|
{ EditorPrefKeys.UseEmbeddedServer, EditorPrefType.Bool },
|
|
|
|
|
{ EditorPrefKeys.LockCursorConfig, EditorPrefType.Bool },
|
|
|
|
|
{ EditorPrefKeys.AutoRegisterEnabled, EditorPrefType.Bool },
|
|
|
|
|
{ EditorPrefKeys.SetupCompleted, EditorPrefType.Bool },
|
|
|
|
|
{ EditorPrefKeys.SetupDismissed, EditorPrefType.Bool },
|
|
|
|
|
{ EditorPrefKeys.CustomToolRegistrationEnabled, EditorPrefType.Bool },
|
|
|
|
|
{ EditorPrefKeys.TelemetryDisabled, EditorPrefType.Bool },
|
Fix HTTP/Stdio Transport UX and Test Bug (#530)
* refactor: Split ParseColorOrDefault into two overloads and change default to Color.white
* Auto-format Python code
* Remove unused Python module
* Refactored VFX functionality into multiple files
Tested everything, works like a charm
* Rename ManageVfx folder to just Vfx
We know what it's managing
* Clean up whitespace on plugin tools and resources
* Make ManageGameObject less of a monolith by splitting it out into different files
* Remove obsolete FindObjectByInstruction method
We also update the namespace for ManageVFX
* Add local test harness for fast developer iteration
Scripts for running the NL/T/GO test suites locally against a GUI Unity
Editor, complementing the CI workflows in .github/workflows/.
Benefits:
- 10-100x faster than CI (no Docker startup)
- Real-time Unity console debugging
- Single test execution for rapid iteration
- Auto-detects HTTP vs stdio transport
Usage:
./scripts/local-test/setup.sh # One-time setup
./scripts/local-test/quick-test.sh NL-0 # Run single test
./scripts/local-test/run-nl-suite-local.sh # Full suite
See scripts/local-test/README.md for details.
Also updated .gitignore to:
- Allow scripts/local-test/ to be tracked
- Ignore generated artifacts (reports/*.xml, .claude/local/, .unity-mcp/)
* Fix issue #525: Save dirty scenes for all test modes
Move SaveDirtyScenesIfNeeded() call outside the PlayMode conditional
so EditMode tests don't get blocked by Unity's "Save Scene" modal dialog.
This prevents MCP from timing out when running EditMode tests with unsaved
scene changes.
* refactor: Consolidate editor state resources into single canonical implementation
Merged EditorStateV2 into EditorState, making get_editor_state the canonical resource. Updated Unity C# to use EditorStateCache directly. Enhanced Python implementation with advice/staleness enrichment, external changes detection, and instance ID inference. Removed duplicate EditorStateV2 resource and legacy fallback mapping.
* Validate editor state with Pydantic models in both C# and Python
Added strongly-typed Pydantic models for EditorStateV2 schema in Python and corresponding C# classes with JsonProperty attributes. Updated C# to serialize using typed classes instead of anonymous objects. Python now validates the editor state payload before returning it, catching schema mismatches early.
* Consolidate run_tests and run_tests_async into single async implementation
Merged run_tests_async into run_tests, making async job-based execution the default behavior. Removed synchronous blocking test execution. Updated RunTests.cs to start test jobs immediately and return job_id for polling. Changed TestJobManager methods to internal visibility. Updated README to reflect single run_tests_async tool. Python implementation now uses async job pattern exclusively.
* Validate test job responses with Pydantic models in Python
* Change resources URI from unity:// to mcpforunity://
It should reduce conflicts with other Unity MCPs that users try, and to comply with Unity's requests regarding use of their company and product name
* Update README with all tools + better listing for resources
* Update other references to resources
* Updated translated doc - unfortunately I cannot verify
* Update the Chinese translation of the dev docks
* Change menu item from Setup Window to Local Setup Window
We now differentiate whether it's HTTP local or remote
* Fix URIs for menu items and tests
* Shouldn't have removed it
* fix: add missing FAST_FAIL_TIMEOUT constant in PluginHub
The FAST_FAIL_TIMEOUT class attribute was referenced on line 149 but never
defined, causing AttributeError on every ping attempt. This error was silently
caught by the broad 'except Exception' handler, causing all fast-fail commands
(read_console, get_editor_state, ping) to fail after 6 seconds of retries with
'ping not answered' error.
Added FAST_FAIL_TIMEOUT = 10 to define a 10-second timeout for fast-fail
commands, matching the intent of the existing fast-fail infrastructure.
* feat(ScriptableObject): enhance dry-run validation for AnimationCurve and Quaternion
Dry-run validation now validates value formats, not just property existence:
- AnimationCurve: Validates structure ({keys:[...]} or direct array), checks
each keyframe is an object, validates numeric fields (time, value, inSlope,
outSlope, inWeight, outWeight) and integer fields (weightedMode)
- Quaternion: Validates array length (3 for Euler, 4 for raw) or object
structure ({x,y,z,w} or {euler:[x,y,z]}), ensures all components are numeric
Refactored shared validation helpers into appropriate locations:
- ParamCoercion: IsNumericToken, ValidateNumericField, ValidateIntegerField
- VectorParsing: ValidateAnimationCurveFormat, ValidateQuaternionFormat
Added comprehensive XML documentation clarifying keyframe field defaults
(all default to 0 except as noted).
Added 5 new dry-run validation tests covering valid and invalid formats
for both AnimationCurve and Quaternion properties.
* test: fix integration tests after merge
- test_refresh_unity_retry_recovery: Mock now handles both refresh_unity and
get_editor_state commands (refresh_unity internally calls get_editor_state
when wait_for_ready=True)
- test_run_tests_async_forwards_params: Mock response now includes required
'mode' field for RunTestsStartResponse Pydantic validation
- test_get_test_job_forwards_job_id: Updated to handle GetTestJobResponse as
Pydantic model instead of dict (use model_dump() for assertions)
* Update warning message to apply to all test modes
Follow-up to PR #527: Since SaveDirtyScenesIfNeeded() now runs for all test modes, update the warning message to say 'tests' instead of 'PlayMode tests'.
* feat(run_tests): add wait_timeout to get_test_job to avoid client loop detection
When polling for test completion, MCP clients like Cursor can detect the
repeated get_test_job calls as 'looping' and terminate the agent.
Added wait_timeout parameter that makes the server wait internally for tests
to complete (polling Unity every 2s) before returning. This dramatically
reduces client-side tool calls from 10-20 down to 1-2, avoiding loop detection.
Usage: get_test_job(job_id='xxx', wait_timeout=30)
- Returns immediately if tests complete within timeout
- Returns current status if timeout expires (client can call again)
- Recommended: 30-60 seconds
* fix: use Pydantic attribute access in test_run_tests_async for merge compatibility
* revert: remove local test harness - will be submitted in separate PR
* fix: stdio transport survives test runs without UI flicker
Root cause: WriteToConfigTests.TearDown() was unconditionally deleting
UseHttpTransport EditorPref even when tests were skipped on Windows
(NUnit runs TearDown even after Assert.Ignore).
Changes:
- Fix WriteToConfigTests to save/restore prefs instead of deleting
- Add centralized ShouldForceUvxRefresh() for local dev path detection
- Clean stale Python build/ artifacts before client configuration
- Improve reload handler flag management to prevent stuck Resuming state
- Show Resuming status during stdio bridge restart
- Initialize client config display on window open
- Add DevModeForceServerRefresh to EditorPrefs window known types
---------
Co-authored-by: Marcus Sanatan <msanatan@gmail.com>
Co-authored-by: Scott Jennings <scott.jennings+CIGINT@cloudimperiumgames.com>
2026-01-08 11:33:22 +08:00
|
|
|
{ EditorPrefKeys.DevModeForceServerRefresh, EditorPrefType.Bool },
|
2025-12-30 01:30:45 +08:00
|
|
|
|
|
|
|
|
// Integer prefs
|
|
|
|
|
{ EditorPrefKeys.UnitySocketPort, EditorPrefType.Int },
|
|
|
|
|
{ EditorPrefKeys.ValidationLevel, EditorPrefType.Int },
|
|
|
|
|
{ EditorPrefKeys.LastUpdateCheck, EditorPrefType.Int },
|
|
|
|
|
{ EditorPrefKeys.LastStdIoUpgradeVersion, EditorPrefType.Int },
|
|
|
|
|
|
|
|
|
|
// String prefs
|
|
|
|
|
{ EditorPrefKeys.EditorWindowActivePanel, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.ClaudeCliPathOverride, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.UvxPathOverride, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.HttpBaseUrl, EditorPrefType.String },
|
HTTP setup overhaul: transport selection (HTTP local/remote vs stdio), safer lifecycle, cleaner UI, better Claude Code integration (#499)
* Avoid blocking Claude CLI status checks on focus
* Fix Claude Code registration to remove existing server before re-registering
When registering with Claude Code, if a UnityMCP server already exists,
remove it first before adding the new registration. This ensures the
transport mode (HTTP vs stdio) is always updated to match the current
UseHttpTransport EditorPref setting.
Previously, if a stdio registration existed and the user tried to register
with HTTP, the command would fail with 'already exists' and the old stdio
configuration would remain unchanged.
* Fix Claude Code transport validation to parse CLI output format correctly
The validation code was incorrectly parsing the output of 'claude mcp get UnityMCP' by looking for JSON format ("transport": "http"), but the CLI actually returns human-readable text format ("Type: http"). This caused the transport mismatch detection to never trigger, allowing stdio to be selected in the UI while HTTP was registered with Claude Code.
Changes:
- Fix parsing logic to check for "Type: http" or "Type: stdio" in CLI output
- Add OnTransportChanged event to refresh client status when transport changes
- Wire up event handler to trigger client status refresh on transport dropdown change
This ensures that when the transport mode in Unity doesn't match what's registered with Claude Code, the UI will correctly show an error status with instructions to re-register.
* Fix Claude Code registration UI blocking and thread safety issues
This commit resolves three issues with Claude Code registration:
1. UI blocking: Removed synchronous CheckStatus() call after registration
that was blocking the editor. Status is now set immediately with async
verification happening in the background.
2. Thread safety: Fixed "can only be called from the main thread" errors
by capturing Application.dataPath and EditorPrefs.GetBool() on the main
thread before spawning async status check tasks.
3. Transport mismatch detection: Transport mode changes now trigger immediate
status checks to detect HTTP/stdio mismatches, instead of waiting for the
45-second refresh interval.
The registration button now turns green immediately after successful
registration without blocking, and properly detects transport mismatches
when switching between HTTP and stdio modes.
* Enforce thread safety for Claude Code status checks at compile time
Address code review feedback by making CheckStatusWithProjectDir thread-safe
by design rather than by convention:
1. Made projectDir and useHttpTransport parameters non-nullable to prevent
accidental background thread calls without captured values
2. Removed nullable fallback to EditorPrefs.GetBool() which would cause
thread safety violations if called from background threads
3. Added ArgumentNullException for null projectDir instead of falling back
to Application.dataPath (which is main-thread only)
4. Added XML documentation clearly stating threading contracts:
- CheckStatus() must be called from main thread
- CheckStatusWithProjectDir() is safe for background threads
5. Removed unreachable else branch in async status check code
These changes make it impossible to misuse the API from background threads,
with compile-time enforcement instead of runtime errors.
* Consolidate local HTTP Start/Stop and auto-start session
* HTTP improvements: Unity-owned server lifecycle + UI polish
* Deterministic HTTP stop via pidfile+token; spawn server in terminal
* Fix review feedback: token validation, host normalization, safer casts
* Fix stop heuristics edge cases; remove dead pid capture
* Fix unity substring guard in stop heuristics
* Fix local server cleanup and connection checks
* Fix read_console default limits; cleanup Unity-managed server vestiges
* Fix unfocused reconnect stalls; fast-fail retryable Unity commands
* Simplify PluginHub reload handling; honor run_tests timeout
* Fix Windows Claude CLI status check threading
2026-01-02 09:08:51 +08:00
|
|
|
{ EditorPrefKeys.HttpTransportScope, EditorPrefType.String },
|
2025-12-30 01:30:45 +08:00
|
|
|
{ EditorPrefKeys.SessionId, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.WebSocketUrlOverride, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.GitUrlOverride, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.PackageDeploySourcePath, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.PackageDeployLastBackupPath, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.PackageDeployLastTargetPath, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.PackageDeployLastSourcePath, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.ServerSrc, EditorPrefType.String },
|
|
|
|
|
{ EditorPrefKeys.LatestKnownVersion, EditorPrefType.String },
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Templates
|
|
|
|
|
private VisualTreeAsset itemTemplate;
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Show the EditorPrefs window
|
|
|
|
|
/// </summary>
|
|
|
|
|
public static void ShowWindow()
|
|
|
|
|
{
|
|
|
|
|
var window = GetWindow<EditorPrefsWindow>("EditorPrefs");
|
|
|
|
|
window.minSize = new Vector2(600, 400);
|
|
|
|
|
window.Show();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void CreateGUI()
|
|
|
|
|
{
|
|
|
|
|
string basePath = AssetPathUtility.GetMcpPackageRootPath();
|
|
|
|
|
|
|
|
|
|
// Load UXML
|
|
|
|
|
var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(
|
|
|
|
|
$"{basePath}/Editor/Windows/EditorPrefs/EditorPrefsWindow.uxml"
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
if (visualTree == null)
|
|
|
|
|
{
|
2026-01-07 13:33:20 +08:00
|
|
|
McpLog.Error("Failed to load EditorPrefsWindow.uxml template");
|
2025-12-30 01:30:45 +08:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Load item template
|
|
|
|
|
itemTemplate = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(
|
|
|
|
|
$"{basePath}/Editor/Windows/EditorPrefs/EditorPrefItem.uxml"
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
if (itemTemplate == null)
|
|
|
|
|
{
|
2026-01-07 13:33:20 +08:00
|
|
|
McpLog.Error("Failed to load EditorPrefItem.uxml template");
|
2025-12-30 01:30:45 +08:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
visualTree.CloneTree(rootVisualElement);
|
|
|
|
|
|
|
|
|
|
// Get references
|
|
|
|
|
scrollView = rootVisualElement.Q<ScrollView>("scroll-view");
|
|
|
|
|
prefsContainer = rootVisualElement.Q<VisualElement>("prefs-container");
|
|
|
|
|
|
|
|
|
|
// Load known MCP keys
|
|
|
|
|
LoadKnownMcpKeys();
|
|
|
|
|
|
|
|
|
|
// Load initial data
|
|
|
|
|
RefreshPrefs();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void LoadKnownMcpKeys()
|
|
|
|
|
{
|
|
|
|
|
knownMcpKeys.Clear();
|
|
|
|
|
var fields = typeof(EditorPrefKeys).GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
|
|
|
|
|
|
|
|
|
|
foreach (var field in fields)
|
|
|
|
|
{
|
|
|
|
|
if (field.IsLiteral && !field.IsInitOnly)
|
|
|
|
|
{
|
|
|
|
|
knownMcpKeys.Add(field.GetValue(null).ToString());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void RefreshPrefs()
|
|
|
|
|
{
|
|
|
|
|
currentPrefs.Clear();
|
|
|
|
|
prefsContainer.Clear();
|
|
|
|
|
|
|
|
|
|
// Get all EditorPrefs keys
|
|
|
|
|
var allKeys = new List<string>();
|
|
|
|
|
|
|
|
|
|
// Always show all MCP keys
|
|
|
|
|
allKeys.AddRange(knownMcpKeys);
|
|
|
|
|
|
|
|
|
|
// Try to find additional MCP keys
|
|
|
|
|
var mcpKeys = GetAllMcpKeys();
|
|
|
|
|
foreach (var key in mcpKeys)
|
|
|
|
|
{
|
|
|
|
|
if (!allKeys.Contains(key))
|
|
|
|
|
{
|
|
|
|
|
allKeys.Add(key);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Sort keys
|
|
|
|
|
allKeys.Sort();
|
|
|
|
|
|
|
|
|
|
// Create items for existing prefs
|
|
|
|
|
foreach (var key in allKeys)
|
|
|
|
|
{
|
|
|
|
|
// Skip Customer UUID but show everything else that's defined
|
|
|
|
|
if (key != EditorPrefKeys.CustomerUuid)
|
|
|
|
|
{
|
|
|
|
|
var item = CreateEditorPrefItem(key);
|
|
|
|
|
if (item != null)
|
|
|
|
|
{
|
|
|
|
|
currentPrefs.Add(item);
|
|
|
|
|
prefsContainer.Add(CreateItemUI(item));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private List<string> GetAllMcpKeys()
|
|
|
|
|
{
|
|
|
|
|
// This is a simplified approach - in reality, getting all EditorPrefs is platform-specific
|
|
|
|
|
// For now, we'll return known MCP keys that might exist
|
|
|
|
|
var keys = new List<string>();
|
|
|
|
|
|
|
|
|
|
// Add some common MCP keys that might not be in EditorPrefKeys
|
|
|
|
|
keys.Add("MCPForUnity.TestKey");
|
|
|
|
|
|
|
|
|
|
// Filter to only those that actually exist
|
|
|
|
|
return keys.Where(EditorPrefs.HasKey).ToList();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private EditorPrefItem CreateEditorPrefItem(string key)
|
|
|
|
|
{
|
|
|
|
|
var item = new EditorPrefItem { Key = key, IsKnown = knownMcpKeys.Contains(key) };
|
|
|
|
|
|
|
|
|
|
// Check if we know the type of this pref
|
|
|
|
|
if (knownPrefTypes.TryGetValue(key, out var knownType))
|
|
|
|
|
{
|
|
|
|
|
// Use the known type
|
|
|
|
|
switch (knownType)
|
|
|
|
|
{
|
|
|
|
|
case EditorPrefType.Bool:
|
|
|
|
|
item.Type = EditorPrefType.Bool;
|
|
|
|
|
item.Value = EditorPrefs.GetBool(key, false).ToString();
|
|
|
|
|
break;
|
|
|
|
|
case EditorPrefType.Int:
|
|
|
|
|
item.Type = EditorPrefType.Int;
|
|
|
|
|
item.Value = EditorPrefs.GetInt(key, 0).ToString();
|
|
|
|
|
break;
|
|
|
|
|
case EditorPrefType.Float:
|
|
|
|
|
item.Type = EditorPrefType.Float;
|
|
|
|
|
item.Value = EditorPrefs.GetFloat(key, 0f).ToString();
|
|
|
|
|
break;
|
|
|
|
|
case EditorPrefType.String:
|
|
|
|
|
item.Type = EditorPrefType.String;
|
|
|
|
|
item.Value = EditorPrefs.GetString(key, "");
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
// Only try to detect type for unknown keys that actually exist
|
|
|
|
|
if (!EditorPrefs.HasKey(key))
|
|
|
|
|
{
|
|
|
|
|
// Key doesn't exist and we don't know its type, skip it
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Unknown pref - try to detect type
|
|
|
|
|
var stringValue = EditorPrefs.GetString(key, "");
|
|
|
|
|
|
|
|
|
|
if (int.TryParse(stringValue, out var intValue))
|
|
|
|
|
{
|
|
|
|
|
item.Type = EditorPrefType.Int;
|
|
|
|
|
item.Value = intValue.ToString();
|
|
|
|
|
}
|
|
|
|
|
else if (float.TryParse(stringValue, out var floatValue))
|
|
|
|
|
{
|
|
|
|
|
item.Type = EditorPrefType.Float;
|
|
|
|
|
item.Value = floatValue.ToString();
|
|
|
|
|
}
|
|
|
|
|
else if (bool.TryParse(stringValue, out var boolValue))
|
|
|
|
|
{
|
|
|
|
|
item.Type = EditorPrefType.Bool;
|
|
|
|
|
item.Value = boolValue.ToString();
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
item.Type = EditorPrefType.String;
|
|
|
|
|
item.Value = stringValue;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return item;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private VisualElement CreateItemUI(EditorPrefItem item)
|
|
|
|
|
{
|
|
|
|
|
if (itemTemplate == null)
|
|
|
|
|
{
|
2026-01-07 13:33:20 +08:00
|
|
|
McpLog.Error("Item template not loaded");
|
2025-12-30 01:30:45 +08:00
|
|
|
return new VisualElement();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var itemElement = itemTemplate.CloneTree();
|
|
|
|
|
|
|
|
|
|
// Set values
|
|
|
|
|
itemElement.Q<Label>("key-label").text = item.Key;
|
|
|
|
|
var valueField = itemElement.Q<TextField>("value-field");
|
|
|
|
|
valueField.value = item.Value;
|
|
|
|
|
|
|
|
|
|
var typeDropdown = itemElement.Q<DropdownField>("type-dropdown");
|
|
|
|
|
typeDropdown.index = (int)item.Type;
|
|
|
|
|
|
|
|
|
|
// Buttons
|
|
|
|
|
var saveButton = itemElement.Q<Button>("save-button");
|
|
|
|
|
|
|
|
|
|
// Callbacks
|
|
|
|
|
saveButton.clicked += () => SavePref(item, valueField.value, (EditorPrefType)typeDropdown.index);
|
|
|
|
|
|
|
|
|
|
return itemElement;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void SavePref(EditorPrefItem item, string newValue, EditorPrefType newType)
|
|
|
|
|
{
|
|
|
|
|
SaveValue(item.Key, newValue, newType);
|
|
|
|
|
RefreshPrefs();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void SaveValue(string key, string value, EditorPrefType type)
|
|
|
|
|
{
|
|
|
|
|
switch (type)
|
|
|
|
|
{
|
|
|
|
|
case EditorPrefType.String:
|
|
|
|
|
EditorPrefs.SetString(key, value);
|
|
|
|
|
break;
|
|
|
|
|
case EditorPrefType.Int:
|
|
|
|
|
if (int.TryParse(value, out var intValue))
|
|
|
|
|
{
|
|
|
|
|
EditorPrefs.SetInt(key, intValue);
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
EditorUtility.DisplayDialog("Error", $"Cannot convert '{value}' to int", "OK");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
break;
|
|
|
|
|
case EditorPrefType.Float:
|
|
|
|
|
if (float.TryParse(value, out var floatValue))
|
|
|
|
|
{
|
|
|
|
|
EditorPrefs.SetFloat(key, floatValue);
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
EditorUtility.DisplayDialog("Error", $"Cannot convert '{value}' to float", "OK");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
break;
|
|
|
|
|
case EditorPrefType.Bool:
|
|
|
|
|
if (bool.TryParse(value, out var boolValue))
|
|
|
|
|
{
|
|
|
|
|
EditorPrefs.SetBool(key, boolValue);
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
EditorUtility.DisplayDialog("Error", $"Cannot convert '{value}' to bool (use 'True' or 'False')", "OK");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Represents an EditorPrefs item
|
|
|
|
|
/// </summary>
|
|
|
|
|
public class EditorPrefItem
|
|
|
|
|
{
|
|
|
|
|
public string Key { get; set; }
|
|
|
|
|
public string Value { get; set; }
|
|
|
|
|
public EditorPrefType Type { get; set; }
|
|
|
|
|
public bool IsKnown { get; set; }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// EditorPrefs value types
|
|
|
|
|
/// </summary>
|
|
|
|
|
public enum EditorPrefType
|
|
|
|
|
{
|
|
|
|
|
String,
|
|
|
|
|
Int,
|
|
|
|
|
Float,
|
|
|
|
|
Bool
|
|
|
|
|
}
|
|
|
|
|
}
|