diff --git a/UnityMcpBridge/Editor/Helpers/GameObjectSerializer.cs b/UnityMcpBridge/Editor/Helpers/GameObjectSerializer.cs new file mode 100644 index 0000000..8a65ada --- /dev/null +++ b/UnityMcpBridge/Editor/Helpers/GameObjectSerializer.cs @@ -0,0 +1,378 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using UnityEditor; +using UnityEngine; +using UnityMcpBridge.Runtime.Serialization; // For Converters + +namespace UnityMcpBridge.Editor.Helpers +{ + /// + /// Handles serialization of GameObjects and Components for MCP responses. + /// Includes reflection helpers and caching for performance. + /// + public static class GameObjectSerializer + { + // --- Data Serialization --- + + /// + /// Creates a serializable representation of a GameObject. + /// + public static object GetGameObjectData(GameObject go) + { + if (go == null) + return null; + return new + { + name = go.name, + instanceID = go.GetInstanceID(), + tag = go.tag, + layer = go.layer, + activeSelf = go.activeSelf, + activeInHierarchy = go.activeInHierarchy, + isStatic = go.isStatic, + scenePath = go.scene.path, // Identify which scene it belongs to + transform = new // Serialize transform components carefully to avoid JSON issues + { + // Serialize Vector3 components individually to prevent self-referencing loops. + // The default serializer can struggle with properties like Vector3.normalized. + position = new + { + x = go.transform.position.x, + y = go.transform.position.y, + z = go.transform.position.z, + }, + localPosition = new + { + x = go.transform.localPosition.x, + y = go.transform.localPosition.y, + z = go.transform.localPosition.z, + }, + rotation = new + { + x = go.transform.rotation.eulerAngles.x, + y = go.transform.rotation.eulerAngles.y, + z = go.transform.rotation.eulerAngles.z, + }, + localRotation = new + { + x = go.transform.localRotation.eulerAngles.x, + y = go.transform.localRotation.eulerAngles.y, + z = go.transform.localRotation.eulerAngles.z, + }, + scale = new + { + x = go.transform.localScale.x, + y = go.transform.localScale.y, + z = go.transform.localScale.z, + }, + forward = new + { + x = go.transform.forward.x, + y = go.transform.forward.y, + z = go.transform.forward.z, + }, + up = new + { + x = go.transform.up.x, + y = go.transform.up.y, + z = go.transform.up.z, + }, + right = new + { + x = go.transform.right.x, + y = go.transform.right.y, + z = go.transform.right.z, + }, + }, + parentInstanceID = go.transform.parent?.gameObject.GetInstanceID() ?? 0, // 0 if no parent + // Optionally include components, but can be large + // components = go.GetComponents().Select(c => GetComponentData(c)).ToList() + // Or just component names: + componentNames = go.GetComponents() + .Select(c => c.GetType().FullName) + .ToList(), + }; + } + + // --- Metadata Caching for Reflection --- + private class CachedMetadata + { + public readonly List SerializableProperties; + public readonly List SerializableFields; + + public CachedMetadata(List properties, List fields) + { + SerializableProperties = properties; + SerializableFields = fields; + } + } + // Key becomes Tuple + private static readonly Dictionary, CachedMetadata> _metadataCache = new Dictionary, CachedMetadata>(); + // --- End Metadata Caching --- + + /// + /// Creates a serializable representation of a Component, attempting to serialize + /// public properties and fields using reflection, with caching and control over non-public fields. + /// + // Add the flag parameter here + public static object GetComponentData(Component c, bool includeNonPublicSerializedFields = true) + { + if (c == null) return null; + Type componentType = c.GetType(); + + var data = new Dictionary + { + { "typeName", componentType.FullName }, + { "instanceID", c.GetInstanceID() } + }; + + // --- Get Cached or Generate Metadata (using new cache key) --- + Tuple cacheKey = new Tuple(componentType, includeNonPublicSerializedFields); + if (!_metadataCache.TryGetValue(cacheKey, out CachedMetadata cachedData)) + { + var propertiesToCache = new List(); + var fieldsToCache = new List(); + + // Traverse the hierarchy from the component type up to MonoBehaviour + Type currentType = componentType; + while (currentType != null && currentType != typeof(MonoBehaviour) && currentType != typeof(object)) + { + // Get properties declared only at the current type level + BindingFlags propFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly; + foreach (var propInfo in currentType.GetProperties(propFlags)) + { + // Basic filtering (readable, not indexer, not transform which is handled elsewhere) + if (!propInfo.CanRead || propInfo.GetIndexParameters().Length > 0 || propInfo.Name == "transform") continue; + // Add if not already added (handles overrides - keep the most derived version) + if (!propertiesToCache.Any(p => p.Name == propInfo.Name)) { + propertiesToCache.Add(propInfo); + } + } + + // Get fields declared only at the current type level (both public and non-public) + BindingFlags fieldFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly; + var declaredFields = currentType.GetFields(fieldFlags); + + // Process the declared Fields for caching + foreach (var fieldInfo in declaredFields) + { + if (fieldInfo.Name.EndsWith("k__BackingField")) continue; // Skip backing fields + + // Add if not already added (handles hiding - keep the most derived version) + if (fieldsToCache.Any(f => f.Name == fieldInfo.Name)) continue; + + bool shouldInclude = false; + if (includeNonPublicSerializedFields) + { + // If TRUE, include Public OR NonPublic with [SerializeField] + shouldInclude = fieldInfo.IsPublic || (fieldInfo.IsPrivate && fieldInfo.IsDefined(typeof(SerializeField), inherit: false)); + } + else // includeNonPublicSerializedFields is FALSE + { + // If FALSE, include ONLY if it is explicitly Public. + shouldInclude = fieldInfo.IsPublic; + } + + if (shouldInclude) + { + fieldsToCache.Add(fieldInfo); + } + } + + // Move to the base type + currentType = currentType.BaseType; + } + // --- End Hierarchy Traversal --- + + cachedData = new CachedMetadata(propertiesToCache, fieldsToCache); + _metadataCache[cacheKey] = cachedData; // Add to cache with combined key + } + // --- End Get Cached or Generate Metadata --- + + // --- Use cached metadata --- + var serializablePropertiesOutput = new Dictionary(); + // Use cached properties + foreach (var propInfo in cachedData.SerializableProperties) + { + // --- Skip known obsolete/problematic Component shortcut properties --- + string propName = propInfo.Name; + if (propName == "rigidbody" || propName == "rigidbody2D" || propName == "camera" || + propName == "light" || propName == "animation" || propName == "constantForce" || + propName == "renderer" || propName == "audio" || propName == "networkView" || + propName == "collider" || propName == "collider2D" || propName == "hingeJoint" || + propName == "particleSystem" || + // Also skip potentially problematic Matrix properties prone to cycles/errors + propName == "worldToLocalMatrix" || propName == "localToWorldMatrix") + { + continue; // Skip these properties + } + // --- End Skip --- + + try + { + object value = propInfo.GetValue(c); + Type propType = propInfo.PropertyType; + AddSerializableValue(serializablePropertiesOutput, propName, propType, value); + } + catch (Exception ex) + { + Debug.LogWarning($"Could not read property {propName} on {componentType.Name}: {ex.Message}"); + } + } + + // Use cached fields + foreach (var fieldInfo in cachedData.SerializableFields) + { + try + { + object value = fieldInfo.GetValue(c); + string fieldName = fieldInfo.Name; + Type fieldType = fieldInfo.FieldType; + AddSerializableValue(serializablePropertiesOutput, fieldName, fieldType, value); + } + catch (Exception ex) + { + Debug.LogWarning($"Could not read field {fieldInfo.Name} on {componentType.Name}: {ex.Message}"); + } + } + // --- End Use cached metadata --- + + if (serializablePropertiesOutput.Count > 0) + { + data["properties"] = serializablePropertiesOutput; + } + + return data; + } + + // Helper function to decide how to serialize different types + private static void AddSerializableValue(Dictionary dict, string name, Type type, object value) + { + // Simplified: Directly use CreateTokenFromValue which uses the serializer + if (value == null) + { + dict[name] = null; + return; + } + + try + { + // Use the helper that employs our custom serializer settings + JToken token = CreateTokenFromValue(value, type); + if (token != null) // Check if serialization succeeded in the helper + { + // Convert JToken back to a basic object structure for the dictionary + dict[name] = ConvertJTokenToPlainObject(token); + } + // If token is null, it means serialization failed and a warning was logged. + } + catch (Exception e) + { + // Catch potential errors during JToken conversion or addition to dictionary + Debug.LogWarning($"[AddSerializableValue] Error processing value for '{name}' (Type: {type.FullName}): {e.Message}. Skipping."); + } + } + + // Helper to convert JToken back to basic object structure + private static object ConvertJTokenToPlainObject(JToken token) + { + if (token == null) return null; + + switch (token.Type) + { + case JTokenType.Object: + var objDict = new Dictionary(); + foreach (var prop in ((JObject)token).Properties()) + { + objDict[prop.Name] = ConvertJTokenToPlainObject(prop.Value); + } + return objDict; + + case JTokenType.Array: + var list = new List(); + foreach (var item in (JArray)token) + { + list.Add(ConvertJTokenToPlainObject(item)); + } + return list; + + case JTokenType.Integer: + return token.ToObject(); // Use long for safety + case JTokenType.Float: + return token.ToObject(); // Use double for safety + case JTokenType.String: + return token.ToObject(); + case JTokenType.Boolean: + return token.ToObject(); + case JTokenType.Date: + return token.ToObject(); + case JTokenType.Guid: + return token.ToObject(); + case JTokenType.Uri: + return token.ToObject(); + case JTokenType.TimeSpan: + return token.ToObject(); + case JTokenType.Bytes: + return token.ToObject(); + case JTokenType.Null: + return null; + case JTokenType.Undefined: + return null; // Treat undefined as null + + default: + // Fallback for simple value types not explicitly listed + if (token is JValue jValue && jValue.Value != null) + { + return jValue.Value; + } + Debug.LogWarning($"Unsupported JTokenType encountered: {token.Type}. Returning null."); + return null; + } + } + + // --- Define custom JsonSerializerSettings for OUTPUT --- + private static readonly JsonSerializerSettings _outputSerializerSettings = new JsonSerializerSettings + { + Converters = new List + { + new Vector3Converter(), + new Vector2Converter(), + new QuaternionConverter(), + new ColorConverter(), + new RectConverter(), + new BoundsConverter(), + new UnityEngineObjectConverter() // Handles serialization of references + }, + ReferenceLoopHandling = ReferenceLoopHandling.Ignore, + // ContractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy() } // Example if needed + }; + private static readonly JsonSerializer _outputSerializer = JsonSerializer.Create(_outputSerializerSettings); + // --- End Define custom JsonSerializerSettings --- + + // Helper to create JToken using the output serializer + private static JToken CreateTokenFromValue(object value, Type type) + { + if (value == null) return JValue.CreateNull(); + + try + { + // Use the pre-configured OUTPUT serializer instance + return JToken.FromObject(value, _outputSerializer); + } + catch (JsonSerializationException e) + { + Debug.LogWarning($"[GameObjectSerializer] Newtonsoft.Json Error serializing value of type {type.FullName}: {e.Message}. Skipping property/field."); + return null; // Indicate serialization failure + } + catch (Exception e) // Catch other unexpected errors + { + Debug.LogWarning($"[GameObjectSerializer] Unexpected error serializing value of type {type.FullName}: {e}. Skipping property/field."); + return null; // Indicate serialization failure + } + } + } +} \ No newline at end of file diff --git a/UnityMcpBridge/Editor/Tools/ManageGameObject.cs b/UnityMcpBridge/Editor/Tools/ManageGameObject.cs index 75c4a62..1e22ebd 100644 --- a/UnityMcpBridge/Editor/Tools/ManageGameObject.cs +++ b/UnityMcpBridge/Editor/Tools/ManageGameObject.cs @@ -9,7 +9,8 @@ using UnityEditor.SceneManagement; using UnityEditorInternal; using UnityEngine; using UnityEngine.SceneManagement; -using UnityMcpBridge.Editor.Helpers; // For Response class +using UnityMcpBridge.Editor.Helpers; // For Response class AND GameObjectSerializer +using UnityMcpBridge.Runtime.Serialization; // <<< Keep for Converters access? Might not be needed here directly namespace UnityMcpBridge.Editor.Tools { @@ -44,10 +45,7 @@ namespace UnityMcpBridge.Editor.Tools JToken parentToken = @params["parent"]; // --- Add parameter for controlling non-public field inclusion --- - // Reverting to original logic, assuming external system will be fixed to send the parameter correctly. bool includeNonPublicSerialized = @params["includeNonPublicSerialized"]?.ToObject() ?? true; // Default to true - // Revised: Explicitly check for null, default to false if null/missing. -- REMOVED - // bool includeNonPublicSerialized = @params["includeNonPublicSerialized"] != null && @params["includeNonPublicSerialized"].ToObject(); // --- End add parameter --- // --- Prefab Redirection Check --- @@ -217,29 +215,21 @@ namespace UnityMcpBridge.Editor.Tools else if (!prefabPath.EndsWith(".prefab", StringComparison.OrdinalIgnoreCase)) { // If it looks like a path but doesn't end with .prefab, assume user forgot it and append it. - // We could also error here, but appending might be more user-friendly. Debug.LogWarning( $"[ManageGameObject.Create] Provided prefabPath '{prefabPath}' does not end with .prefab. Assuming it's missing and appending." ); prefabPath += ".prefab"; - // Note: This path might still not exist, AssetDatabase.LoadAssetAtPath will handle that. } - // Removed the early return error for missing .prefab ending. - // The logic above now handles finding or assuming the .prefab extension. - GameObject prefabAsset = AssetDatabase.LoadAssetAtPath(prefabPath); if (prefabAsset != null) { try { - // Instantiate the prefab, initially place it at the root - // Parent will be set later if specified newGo = PrefabUtility.InstantiatePrefab(prefabAsset) as GameObject; if (newGo == null) { - // This might happen if the asset exists but isn't a valid GameObject prefab somehow Debug.LogError( $"[ManageGameObject.Create] Failed to instantiate prefab at '{prefabPath}', asset might be corrupted or not a GameObject." ); @@ -248,13 +238,11 @@ namespace UnityMcpBridge.Editor.Tools ); } - // Name the instance based on the 'name' parameter, not the prefab's default name if (!string.IsNullOrEmpty(name)) { newGo.name = name; } - // Register Undo for prefab instantiation Undo.RegisterCreatedObjectUndo( newGo, $"Instantiate Prefab '{prefabAsset.name}' as '{newGo.name}'" @@ -272,12 +260,9 @@ namespace UnityMcpBridge.Editor.Tools } else { - // Only return error if prefabPath was specified but not found. - // If prefabPath was empty/null, we proceed to create primitive/empty. Debug.LogWarning( $"[ManageGameObject.Create] Prefab asset not found at path: '{prefabPath}'. Will proceed to create new object if specified." ); - // Do not return error here, allow fallback to primitive/empty creation } } @@ -292,7 +277,6 @@ namespace UnityMcpBridge.Editor.Tools PrimitiveType type = (PrimitiveType) Enum.Parse(typeof(PrimitiveType), primitiveType, true); newGo = GameObject.CreatePrimitive(type); - // Set name *after* creation for primitives if (!string.IsNullOrEmpty(name)) newGo.name = name; else @@ -326,22 +310,17 @@ namespace UnityMcpBridge.Editor.Tools createdNewObject = true; } - // Record creation for Undo *only* if we created a new object if (createdNewObject) { Undo.RegisterCreatedObjectUndo(newGo, $"Create GameObject '{newGo.name}'"); } } - // --- Common Setup (Parent, Transform, Tag, Components) - Applied AFTER object exists --- if (newGo == null) { - // Should theoretically not happen if logic above is correct, but safety check. return Response.Error("Failed to create or instantiate the GameObject."); } - // Record potential changes to the existing prefab instance or the new GO - // Record transform separately in case parent changes affect it Undo.RecordObject(newGo.transform, "Set GameObject Transform"); Undo.RecordObject(newGo, "Set GameObject Properties"); @@ -373,7 +352,6 @@ namespace UnityMcpBridge.Editor.Tools // Set Tag (added for create action) if (!string.IsNullOrEmpty(tag)) { - // Similar logic as in ModifyGameObject for setting/creating tags string tagToSet = string.IsNullOrEmpty(tag) ? "Untagged" : tag; try { @@ -470,16 +448,13 @@ namespace UnityMcpBridge.Editor.Tools if (createdNewObject && saveAsPrefab) { string finalPrefabPath = prefabPath; // Use a separate variable for saving path - // This check should now happen *before* attempting to save if (string.IsNullOrEmpty(finalPrefabPath)) { - // Clean up the created object before returning error UnityEngine.Object.DestroyImmediate(newGo); return Response.Error( "'prefabPath' is required when 'saveAsPrefab' is true and creating a new object." ); } - // Ensure the *saving* path ends with .prefab if (!finalPrefabPath.EndsWith(".prefab", StringComparison.OrdinalIgnoreCase)) { Debug.Log( @@ -488,16 +463,8 @@ namespace UnityMcpBridge.Editor.Tools finalPrefabPath += ".prefab"; } - // Removed the error check here as we now ensure the extension exists - // if (!prefabPath.EndsWith(".prefab", StringComparison.OrdinalIgnoreCase)) - // { - // UnityEngine.Object.DestroyImmediate(newGo); - // return Response.Error($"'prefabPath' must end with '.prefab'. Provided: '{prefabPath}'"); - // } - try { - // Ensure directory exists using the final saving path string directoryPath = System.IO.Path.GetDirectoryName(finalPrefabPath); if ( !string.IsNullOrEmpty(directoryPath) @@ -511,7 +478,6 @@ namespace UnityMcpBridge.Editor.Tools ); } - // Use SaveAsPrefabAssetAndConnect with the final saving path finalInstance = PrefabUtility.SaveAsPrefabAssetAndConnect( newGo, finalPrefabPath, @@ -520,7 +486,6 @@ namespace UnityMcpBridge.Editor.Tools if (finalInstance == null) { - // Destroy the original if saving failed somehow (shouldn't usually happen if path is valid) UnityEngine.Object.DestroyImmediate(newGo); return Response.Error( $"Failed to save GameObject '{name}' as prefab at '{finalPrefabPath}'. Check path and permissions." @@ -529,21 +494,16 @@ namespace UnityMcpBridge.Editor.Tools Debug.Log( $"[ManageGameObject.Create] GameObject '{name}' saved as prefab to '{finalPrefabPath}' and instance connected." ); - // Mark the new prefab asset as dirty? Not usually necessary, SaveAsPrefabAsset handles it. - // EditorUtility.SetDirty(finalInstance); // Instance is handled by SaveAsPrefabAssetAndConnect } catch (Exception e) { - // Clean up the instance if prefab saving fails UnityEngine.Object.DestroyImmediate(newGo); // Destroy the original attempt return Response.Error($"Error saving prefab '{finalPrefabPath}': {e.Message}"); } } - // Select the instance in the scene (either prefab instance or newly created/saved one) Selection.activeGameObject = finalInstance; - // Determine appropriate success message using the potentially updated or original path string messagePrefabPath = finalInstance == null ? originalPrefabPath @@ -568,8 +528,8 @@ namespace UnityMcpBridge.Editor.Tools $"GameObject '{finalInstance.name}' created successfully in scene."; } - // Return data for the instance in the scene - return Response.Success(successMessage, GetGameObjectData(finalInstance)); + // Use the new serializer helper + return Response.Success(successMessage, Helpers.GameObjectSerializer.GetGameObjectData(finalInstance)); } private static object ModifyGameObject( @@ -586,7 +546,6 @@ namespace UnityMcpBridge.Editor.Tools ); } - // Record state for Undo *before* modifications Undo.RecordObject(targetGo.transform, "Modify GameObject Transform"); Undo.RecordObject(targetGo, "Modify GameObject Properties"); @@ -618,7 +577,6 @@ namespace UnityMcpBridge.Editor.Tools { return Response.Error($"New parent ('{parentToken}') not found."); } - // Check for hierarchy loops if (newParentGo != null && newParentGo.transform.IsChildOf(targetGo.transform)) { return Response.Error( @@ -642,22 +600,16 @@ namespace UnityMcpBridge.Editor.Tools // Change Tag (using consolidated 'tag' parameter) string tag = @params["tag"]?.ToString(); - // Only attempt to change tag if a non-null tag is provided and it's different from the current one. - // Allow setting an empty string to remove the tag (Unity uses "Untagged"). if (tag != null && targetGo.tag != tag) { - // Ensure the tag is not empty, if empty, it means "Untagged" implicitly string tagToSet = string.IsNullOrEmpty(tag) ? "Untagged" : tag; - try { - // First attempt to set the tag targetGo.tag = tagToSet; modified = true; } catch (UnityException ex) { - // Check if the error is specifically because the tag doesn't exist if (ex.Message.Contains("is not defined")) { Debug.LogWarning( @@ -665,21 +617,15 @@ namespace UnityMcpBridge.Editor.Tools ); try { - // Attempt to create the tag using internal utility InternalEditorUtility.AddTag(tagToSet); - // Wait a frame maybe? Not strictly necessary but sometimes helps editor updates. - // yield return null; // Cannot yield here, editor script limitation - - // Retry setting the tag immediately after creation targetGo.tag = tagToSet; - modified = true; // Mark as modified on successful retry + modified = true; Debug.Log( $"[ManageGameObject] Tag '{tagToSet}' created and assigned successfully." ); } catch (Exception innerEx) { - // Handle failure during tag creation or the second assignment attempt Debug.LogError( $"[ManageGameObject] Failed to create or assign tag '{tagToSet}' after attempting creation: {innerEx.Message}" ); @@ -690,7 +636,6 @@ namespace UnityMcpBridge.Editor.Tools } else { - // If the exception was for a different reason, return the original error return Response.Error($"Failed to set tag to '{tagToSet}': {ex.Message}."); } } @@ -736,7 +681,6 @@ namespace UnityMcpBridge.Editor.Tools } // --- Component Modifications --- - // Note: These might need more specific Undo recording per component // Remove Components if (@params["componentsToRemove"] is JArray componentsToRemoveArray) @@ -759,7 +703,6 @@ namespace UnityMcpBridge.Editor.Tools { foreach (var compToken in componentsToAddArrayModify) { - // ... (parsing logic as in CreateGameObject) ... string typeName = null; JObject properties = null; if (compToken.Type == JTokenType.String) @@ -803,16 +746,18 @@ namespace UnityMcpBridge.Editor.Tools if (!modified) { + // Use the new serializer helper return Response.Success( $"No modifications applied to GameObject '{targetGo.name}'.", - GetGameObjectData(targetGo) + Helpers.GameObjectSerializer.GetGameObjectData(targetGo) ); } EditorUtility.SetDirty(targetGo); // Mark scene as dirty + // Use the new serializer helper return Response.Success( $"GameObject '{targetGo.name}' modified successfully.", - GetGameObjectData(targetGo) + Helpers.GameObjectSerializer.GetGameObjectData(targetGo) ); } @@ -875,7 +820,8 @@ namespace UnityMcpBridge.Editor.Tools return Response.Success("No matching GameObjects found.", new List()); } - var results = foundObjects.Select(go => GetGameObjectData(go)).ToList(); + // Use the new serializer helper + var results = foundObjects.Select(go => Helpers.GameObjectSerializer.GetGameObjectData(go)).ToList(); return Response.Success($"Found {results.Count} GameObject(s).", results); } @@ -892,8 +838,8 @@ namespace UnityMcpBridge.Editor.Tools try { Component[] components = targetGo.GetComponents(); - // Pass the flag to GetComponentData - var componentData = components.Select(c => GetComponentData(c, includeNonPublicSerialized)).ToList(); + // Use the new serializer helper and pass the flag + var componentData = components.Select(c => Helpers.GameObjectSerializer.GetComponentData(c, includeNonPublicSerialized)).ToList(); return Response.Success( $"Retrieved {componentData.Count} components from '{targetGo.name}'.", componentData @@ -957,9 +903,10 @@ namespace UnityMcpBridge.Editor.Tools return addResult; // Return error EditorUtility.SetDirty(targetGo); + // Use the new serializer helper return Response.Success( $"Component '{typeName}' added to '{targetGo.name}'.", - GetGameObjectData(targetGo) + Helpers.GameObjectSerializer.GetGameObjectData(targetGo) ); // Return updated GO data } @@ -1003,9 +950,10 @@ namespace UnityMcpBridge.Editor.Tools return removeResult; // Return error EditorUtility.SetDirty(targetGo); + // Use the new serializer helper return Response.Success( $"Component '{typeName}' removed from '{targetGo.name}'.", - GetGameObjectData(targetGo) + Helpers.GameObjectSerializer.GetGameObjectData(targetGo) ); } @@ -1051,9 +999,10 @@ namespace UnityMcpBridge.Editor.Tools return setResult; // Return error EditorUtility.SetDirty(targetGo); + // Use the new serializer helper return Response.Success( $"Properties set for component '{compName}' on '{targetGo.name}'.", - GetGameObjectData(targetGo) + Helpers.GameObjectSerializer.GetGameObjectData(targetGo) ); } @@ -1330,11 +1279,6 @@ namespace UnityMcpBridge.Editor.Tools } } - // Check if component already exists (optional, depending on desired behavior) - // if (targetGo.GetComponent(componentType) != null) { - // return Response.Error($"Component '{typeName}' already exists on '{targetGo.name}'."); - // } - try { // Use Undo.AddComponent for undo support @@ -1454,8 +1398,6 @@ namespace UnityMcpBridge.Editor.Tools Debug.LogWarning( $"[ManageGameObject] Could not set property '{propName}' on component '{compName}' ('{targetComponent.GetType().Name}'). Property might not exist, be read-only, or type mismatch." ); - // Optionally return an error here instead of just logging - // return Response.Error($"Could not set property '{propName}' on component '{compName}'."); } } catch (Exception e) @@ -1463,8 +1405,6 @@ namespace UnityMcpBridge.Editor.Tools Debug.LogError( $"[ManageGameObject] Error setting property '{propName}' on '{compName}': {e.Message}" ); - // Optionally return an error here - // return Response.Error($"Error setting property '{propName}' on '{compName}': {e.Message}"); } } EditorUtility.SetDirty(targetComponent); @@ -1480,43 +1420,71 @@ namespace UnityMcpBridge.Editor.Tools BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase; + // --- Use a dedicated serializer for input conversion --- + // Define this somewhere accessible, maybe static readonly field + JsonSerializerSettings inputSerializerSettings = new JsonSerializerSettings + { + Converters = new List + { + // Add specific converters needed for INPUT deserialization if different from output + new Vector3Converter(), + new Vector2Converter(), + new QuaternionConverter(), + new ColorConverter(), + new RectConverter(), + new BoundsConverter(), + new UnityEngineObjectConverter() // Crucial for finding references from instructions + } + // No ReferenceLoopHandling needed typically for input + }; + JsonSerializer inputSerializer = JsonSerializer.Create(inputSerializerSettings); + // --- End Serializer Setup --- + try { // Handle special case for materials with dot notation (material.property) - // Examples: material.color, sharedMaterial.color, materials[0].color if (memberName.Contains('.') || memberName.Contains('[')) { - return SetNestedProperty(target, memberName, value); + // Pass the inputSerializer down for nested conversions + return SetNestedProperty(target, memberName, value, inputSerializer); } PropertyInfo propInfo = type.GetProperty(memberName, flags); if (propInfo != null && propInfo.CanWrite) { - object convertedValue = ConvertJTokenToType(value, propInfo.PropertyType); - if (convertedValue != null) + // Use the inputSerializer for conversion + object convertedValue = ConvertJTokenToType(value, propInfo.PropertyType, inputSerializer); + if (convertedValue != null || value.Type == JTokenType.Null) // Allow setting null { propInfo.SetValue(target, convertedValue); return true; } + else { + Debug.LogWarning($"[SetProperty] Conversion failed for property '{memberName}' (Type: {propInfo.PropertyType.Name}) from token: {value.ToString(Formatting.None)}"); + } } else { FieldInfo fieldInfo = type.GetField(memberName, flags); - if (fieldInfo != null) + if (fieldInfo != null) // Check if !IsLiteral? { - object convertedValue = ConvertJTokenToType(value, fieldInfo.FieldType); - if (convertedValue != null) + // Use the inputSerializer for conversion + object convertedValue = ConvertJTokenToType(value, fieldInfo.FieldType, inputSerializer); + if (convertedValue != null || value.Type == JTokenType.Null) // Allow setting null { fieldInfo.SetValue(target, convertedValue); return true; } + else { + Debug.LogWarning($"[SetProperty] Conversion failed for field '{memberName}' (Type: {fieldInfo.FieldType.Name}) from token: {value.ToString(Formatting.None)}"); + } } } } catch (Exception ex) { Debug.LogError( - $"[SetProperty] Failed to set '{memberName}' on {type.Name}: {ex.Message}" + $"[SetProperty] Failed to set '{memberName}' on {type.Name}: {ex.Message}\nToken: {value.ToString(Formatting.None)}" ); } return false; @@ -1525,7 +1493,8 @@ namespace UnityMcpBridge.Editor.Tools /// /// Sets a nested property using dot notation (e.g., "material.color") or array access (e.g., "materials[0]") /// - private static bool SetNestedProperty(object target, string path, JToken value) + // Pass the input serializer for conversions + private static bool SetNestedProperty(object target, string path, JToken value, JsonSerializer inputSerializer) { try { @@ -1546,7 +1515,6 @@ namespace UnityMcpBridge.Editor.Tools bool isArray = false; int arrayIndex = -1; - // Check if this part contains array indexing if (part.Contains("[")) { int startBracket = part.IndexOf('['); @@ -1565,7 +1533,6 @@ namespace UnityMcpBridge.Editor.Tools } } - // Get the property/field PropertyInfo propInfo = currentType.GetProperty(part, flags); FieldInfo fieldInfo = null; if (propInfo == null) @@ -1580,13 +1547,11 @@ namespace UnityMcpBridge.Editor.Tools } } - // Get the value currentObject = propInfo != null ? propInfo.GetValue(currentObject) : fieldInfo.GetValue(currentObject); - // If the current property is null, we need to stop if (currentObject == null) { Debug.LogWarning( @@ -1595,7 +1560,6 @@ namespace UnityMcpBridge.Editor.Tools return false; } - // If this is an array/list access, get the element at the index if (isArray) { if (currentObject is Material[]) @@ -1630,8 +1594,6 @@ namespace UnityMcpBridge.Editor.Tools return false; } } - - // Update type for next iteration currentType = currentObject.GetType(); } @@ -1641,94 +1603,41 @@ namespace UnityMcpBridge.Editor.Tools // Special handling for Material properties (shader properties) if (currentObject is Material material && finalPart.StartsWith("_")) { - // Handle various material property types + // Use the serializer to convert the JToken value first if (value is JArray jArray) { - if (jArray.Count == 4) // Color with alpha - { - Color color = new Color( - jArray[0].ToObject(), - jArray[1].ToObject(), - jArray[2].ToObject(), - jArray[3].ToObject() - ); - material.SetColor(finalPart, color); - return true; - } - else if (jArray.Count == 3) // Color without alpha - { - Color color = new Color( - jArray[0].ToObject(), - jArray[1].ToObject(), - jArray[2].ToObject(), - 1.0f - ); - material.SetColor(finalPart, color); - return true; - } - else if (jArray.Count == 2) // Vector2 - { - Vector2 vec = new Vector2( - jArray[0].ToObject(), - jArray[1].ToObject() - ); - material.SetVector(finalPart, vec); - return true; - } - else if (jArray.Count == 4) // Vector4 - { - Vector4 vec = new Vector4( - jArray[0].ToObject(), - jArray[1].ToObject(), - jArray[2].ToObject(), - jArray[3].ToObject() - ); - material.SetVector(finalPart, vec); - return true; + // Try converting to known types that SetColor/SetVector accept + if (jArray.Count == 4) { + try { Color color = value.ToObject(inputSerializer); material.SetColor(finalPart, color); return true; } catch {} + try { Vector4 vec = value.ToObject(inputSerializer); material.SetVector(finalPart, vec); return true; } catch {} + } else if (jArray.Count == 3) { + try { Color color = value.ToObject(inputSerializer); material.SetColor(finalPart, color); return true; } catch {} // ToObject handles conversion to Color + } else if (jArray.Count == 2) { + try { Vector2 vec = value.ToObject(inputSerializer); material.SetVector(finalPart, vec); return true; } catch {} } } else if (value.Type == JTokenType.Float || value.Type == JTokenType.Integer) { - material.SetFloat(finalPart, value.ToObject()); - return true; + try { material.SetFloat(finalPart, value.ToObject(inputSerializer)); return true; } catch {} } else if (value.Type == JTokenType.Boolean) { - material.SetFloat(finalPart, value.ToObject() ? 1f : 0f); - return true; + try { material.SetFloat(finalPart, value.ToObject(inputSerializer) ? 1f : 0f); return true; } catch {} } else if (value.Type == JTokenType.String) { - // Might be a texture path - string texturePath = value.ToString(); - if ( - texturePath.EndsWith(".png") - || texturePath.EndsWith(".jpg") - || texturePath.EndsWith(".tga") - ) - { - Texture2D texture = AssetDatabase.LoadAssetAtPath( - texturePath - ); - if (texture != null) - { - material.SetTexture(finalPart, texture); - return true; - } - } - else - { - // Materials don't have SetString, use SetTextureOffset as workaround or skip - // material.SetString(finalPart, texturePath); - Debug.LogWarning( - $"[SetNestedProperty] String values not directly supported for material property {finalPart}" - ); - return false; - } + // Try converting to Texture using the serializer/converter + try { + Texture texture = value.ToObject(inputSerializer); + if (texture != null) { + material.SetTexture(finalPart, texture); + return true; + } + } catch {} } Debug.LogWarning( - $"[SetNestedProperty] Unsupported material property value type: {value.Type} for {finalPart}" + $"[SetNestedProperty] Unsupported or failed conversion for material property '{finalPart}' from value: {value.ToString(Formatting.None)}" ); return false; } @@ -1737,32 +1646,37 @@ namespace UnityMcpBridge.Editor.Tools PropertyInfo finalPropInfo = currentType.GetProperty(finalPart, flags); if (finalPropInfo != null && finalPropInfo.CanWrite) { - object convertedValue = ConvertJTokenToType(value, finalPropInfo.PropertyType); - if (convertedValue != null) + // Use the inputSerializer for conversion + object convertedValue = ConvertJTokenToType(value, finalPropInfo.PropertyType, inputSerializer); + if (convertedValue != null || value.Type == JTokenType.Null) { finalPropInfo.SetValue(currentObject, convertedValue); return true; } + else { + Debug.LogWarning($"[SetNestedProperty] Final conversion failed for property '{finalPart}' (Type: {finalPropInfo.PropertyType.Name}) from token: {value.ToString(Formatting.None)}"); + } } else { FieldInfo finalFieldInfo = currentType.GetField(finalPart, flags); if (finalFieldInfo != null) { - object convertedValue = ConvertJTokenToType( - value, - finalFieldInfo.FieldType - ); - if (convertedValue != null) + // Use the inputSerializer for conversion + object convertedValue = ConvertJTokenToType(value, finalFieldInfo.FieldType, inputSerializer); + if (convertedValue != null || value.Type == JTokenType.Null) { finalFieldInfo.SetValue(currentObject, convertedValue); return true; } + else { + Debug.LogWarning($"[SetNestedProperty] Final conversion failed for field '{finalPart}' (Type: {finalFieldInfo.FieldType.Name}) from token: {value.ToString(Formatting.None)}"); + } } else { Debug.LogWarning( - $"[SetNestedProperty] Could not find final property or field '{finalPart}' on type '{currentType.Name}'" + $"[SetNestedProperty] Could not find final writable property or field '{finalPart}' on type '{currentType.Name}'" ); } } @@ -1770,19 +1684,19 @@ namespace UnityMcpBridge.Editor.Tools catch (Exception ex) { Debug.LogError( - $"[SetNestedProperty] Error setting nested property '{path}': {ex.Message}" + $"[SetNestedProperty] Error setting nested property '{path}': {ex.Message}\nToken: {value.ToString(Formatting.None)}" ); } return false; } + /// /// Split a property path into parts, handling both dot notation and array indexers /// private static string[] SplitPropertyPath(string path) { - // Handle complex paths with both dots and array indexers List parts = new List(); int startIndex = 0; bool inBrackets = false; @@ -1801,265 +1715,261 @@ namespace UnityMcpBridge.Editor.Tools } else if (c == '.' && !inBrackets) { - // Found a dot separator outside of brackets parts.Add(path.Substring(startIndex, i - startIndex)); startIndex = i + 1; } } - - // Add the final part if (startIndex < path.Length) { parts.Add(path.Substring(startIndex)); } - return parts.ToArray(); } /// - /// Simple JToken to Type conversion for common Unity types. + /// Simple JToken to Type conversion for common Unity types, using JsonSerializer. /// - private static object ConvertJTokenToType(JToken token, Type targetType) + // Pass the input serializer + private static object ConvertJTokenToType(JToken token, Type targetType, JsonSerializer inputSerializer) { + if (token == null || token.Type == JTokenType.Null) + { + if (targetType.IsValueType && Nullable.GetUnderlyingType(targetType) == null) + { + Debug.LogWarning($"Cannot assign null to non-nullable value type {targetType.Name}. Returning default value."); + return Activator.CreateInstance(targetType); + } + return null; + } + try { - // Unwrap nested material properties if we're assigning to a Material - if (typeof(Material).IsAssignableFrom(targetType) && token is JObject materialProps) - { - // Handle case where we're passing shader properties directly in a nested object - string materialPath = token["path"]?.ToString(); - if (!string.IsNullOrEmpty(materialPath)) - { -#if UNITY_EDITOR // AssetDatabase is editor-only - // Load the material by path - Material material = AssetDatabase.LoadAssetAtPath(materialPath); - if (material != null) - { - // If there are additional properties, set them - foreach (var prop in materialProps.Properties()) - { - if (prop.Name != "path") - { - SetProperty(material, prop.Name, prop.Value); - } - } - return material; - } - else - { - Debug.LogWarning( - $"[ConvertJTokenToType] Could not load material at path: '{materialPath}'" - ); - return null; - } -#else - Debug.LogWarning("[ConvertJTokenToType] Material loading by path is only supported in the Unity Editor."); - return null; -#endif - } - - // If no path is specified, could be a dynamic material or instance set by reference - // In a build, we can't load by path, so we rely on direct reference or null. - return null; - } - - // Basic types first - if (targetType == typeof(string)) - return token.ToObject(); - if (targetType == typeof(int)) - return token.ToObject(); - if (targetType == typeof(float)) - return token.ToObject(); - if (targetType == typeof(bool)) - return token.ToObject(); - - // Vector/Quaternion/Color types - if (targetType == typeof(Vector2) && token is JArray arrV2 && arrV2.Count == 2) - return new Vector2(arrV2[0].ToObject(), arrV2[1].ToObject()); - if (targetType == typeof(Vector3) && token is JArray arrV3 && arrV3.Count == 3) - return new Vector3( - arrV3[0].ToObject(), - arrV3[1].ToObject(), - arrV3[2].ToObject() - ); - if (targetType == typeof(Vector4) && token is JArray arrV4 && arrV4.Count == 4) - return new Vector4( - arrV4[0].ToObject(), - arrV4[1].ToObject(), - arrV4[2].ToObject(), - arrV4[3].ToObject() - ); - if (targetType == typeof(Quaternion) && token is JArray arrQ && arrQ.Count == 4) - return new Quaternion( - arrQ[0].ToObject(), - arrQ[1].ToObject(), - arrQ[2].ToObject(), - arrQ[3].ToObject() - ); - if (targetType == typeof(Color) && token is JArray arrC && arrC.Count >= 3) // Allow RGB or RGBA - return new Color( - arrC[0].ToObject(), - arrC[1].ToObject(), - arrC[2].ToObject(), - arrC.Count > 3 ? arrC[3].ToObject() : 1.0f - ); - - // Enum types - if (targetType.IsEnum) - return Enum.Parse(targetType, token.ToString(), true); // Case-insensitive enum parsing - - // Handle assigning Unity Objects (Assets, Scene Objects, Components) - if (typeof(UnityEngine.Object).IsAssignableFrom(targetType)) - { - // CASE 1: Reference is a JSON Object specifying a scene object/component find criteria - if (token is JObject refObject) - { - JToken findToken = refObject["find"]; - string findMethod = - refObject["method"]?.ToString() ?? "by_id_or_name_or_path"; // Default search - string componentTypeName = refObject["component"]?.ToString(); - - if (findToken == null) - { - Debug.LogWarning( - $"[ConvertJTokenToType] Reference object missing 'find' property: {token}" - ); - return null; - } - - // Find the target GameObject - // Pass 'searchInactive: true' for internal lookups to be more robust - JObject findParams = new JObject(); - findParams["searchInactive"] = true; - GameObject foundGo = FindObjectInternal(findToken, findMethod, findParams); - - if (foundGo == null) - { - Debug.LogWarning( - $"[ConvertJTokenToType] Could not find GameObject specified by reference object: {token}" - ); - return null; - } - - // If a component type is specified, try to get it - if (!string.IsNullOrEmpty(componentTypeName)) - { - Type compType = FindType(componentTypeName); - if (compType == null) - { - Debug.LogWarning( - $"[ConvertJTokenToType] Could not find component type '{componentTypeName}' specified in reference object: {token}" - ); - return null; - } - - // Ensure the targetType is assignable from the found component type - if (!targetType.IsAssignableFrom(compType)) - { - Debug.LogWarning( - $"[ConvertJTokenToType] Found component '{componentTypeName}' but it is not assignable to the target property type '{targetType.Name}'. Reference: {token}" - ); - return null; - } - - Component foundComp = foundGo.GetComponent(compType); - if (foundComp == null) - { - Debug.LogWarning( - $"[ConvertJTokenToType] Found GameObject '{foundGo.name}' but could not find component '{componentTypeName}' on it. Reference: {token}" - ); - return null; - } - return foundComp; // Return the found component - } - else - { - // Otherwise, return the GameObject itself, ensuring it's assignable - if (!targetType.IsAssignableFrom(typeof(GameObject))) - { - Debug.LogWarning( - $"[ConvertJTokenToType] Found GameObject '{foundGo.name}' but it is not assignable to the target property type '{targetType.Name}' (component name was not specified). Reference: {token}" - ); - return null; - } - return foundGo; // Return the found GameObject - } - } - // CASE 2: Reference is a string, assume it's an asset path - else if (token.Type == JTokenType.String) - { - string assetPath = token.ToString(); - if (!string.IsNullOrEmpty(assetPath)) - { -#if UNITY_EDITOR // AssetDatabase is editor-only - // Attempt to load the asset from the provided path using the target type - UnityEngine.Object loadedAsset = AssetDatabase.LoadAssetAtPath( - assetPath, - targetType - ); - if (loadedAsset != null) - { - return loadedAsset; // Return the loaded asset if successful - } - else - { - // Log a warning if the asset could not be found at the path - Debug.LogWarning( - $"[ConvertJTokenToType] Could not load asset of type '{targetType.Name}' from path: '{assetPath}'. Make sure the path is correct and the asset exists."); - return null; - } -#else - Debug.LogWarning($"[ConvertJTokenToType] Asset loading by path ('{assetPath}') is only supported in the Unity Editor."); - return null; -#endif - } - else - { - // Handle cases where an empty string might be intended to clear the reference - return null; // Assign null if the path is empty - } - } - // CASE 3: Reference is null or empty JToken, assign null - else if ( - token.Type == JTokenType.Null - || string.IsNullOrEmpty(token.ToString()) - ) - { - return null; - } - // CASE 4: Invalid format for Unity Object reference - else - { - Debug.LogWarning( - $"[ConvertJTokenToType] Expected a string asset path or a reference object to assign Unity Object of type '{targetType.Name}', but received token type '{token.Type}'. Value: {token}" - ); - return null; - } - } - - // Fallback: Try direct conversion (might work for other simple value types) - // Be cautious here, this might throw errors for complex types not handled above - try - { - return token.ToObject(targetType); - } - catch (Exception directConversionEx) - { - Debug.LogWarning( - $"[ConvertJTokenToType] Direct conversion failed for JToken '{token}' to type '{targetType.Name}': {directConversionEx.Message}. Specific handling might be needed." - ); - return null; - } + // Use the provided serializer instance which includes our custom converters + return token.ToObject(targetType, inputSerializer); + } + catch (JsonSerializationException jsonEx) + { + Debug.LogError($"JSON Deserialization Error converting token to {targetType.FullName}: {jsonEx.Message}\nToken: {token.ToString(Formatting.None)}"); + // Optionally re-throw or return null/default + // return targetType.IsValueType ? Activator.CreateInstance(targetType) : null; + throw; // Re-throw to indicate failure higher up + } + catch (ArgumentException argEx) + { + Debug.LogError($"Argument Error converting token to {targetType.FullName}: {argEx.Message}\nToken: {token.ToString(Formatting.None)}"); + throw; } catch (Exception ex) { - Debug.LogWarning( - $"[ConvertJTokenToType] Could not convert JToken '{token}' to type '{targetType.Name}': {ex.Message}" - ); - return null; + Debug.LogError($"Unexpected error converting token to {targetType.FullName}: {ex}\nToken: {token.ToString(Formatting.None)}"); + throw; } + // If ToObject succeeded, it would have returned. If it threw, we wouldn't reach here. + // This fallback logic is likely unreachable if ToObject covers all cases or throws on failure. + // Debug.LogWarning($"Conversion failed for token to {targetType.FullName}. Token: {token.ToString(Formatting.None)}"); + // return targetType.IsValueType ? Activator.CreateInstance(targetType) : null; } + // --- ParseJTokenTo... helpers are likely redundant now with the serializer approach --- + // Keep them temporarily for reference or if specific fallback logic is ever needed. + + private static Vector3 ParseJTokenToVector3(JToken token) + { + // ... (implementation - likely replaced by Vector3Converter) ... + // Consider removing these if the serializer handles them reliably. + if (token is JObject obj && obj.ContainsKey("x") && obj.ContainsKey("y") && obj.ContainsKey("z")) + { + return new Vector3(obj["x"].ToObject(), obj["y"].ToObject(), obj["z"].ToObject()); + } + if (token is JArray arr && arr.Count >= 3) + { + return new Vector3(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject()); + } + Debug.LogWarning($"Could not parse JToken '{token}' as Vector3 using fallback. Returning Vector3.zero."); + return Vector3.zero; + + } + private static Vector2 ParseJTokenToVector2(JToken token) + { + // ... (implementation - likely replaced by Vector2Converter) ... + if (token is JObject obj && obj.ContainsKey("x") && obj.ContainsKey("y")) + { + return new Vector2(obj["x"].ToObject(), obj["y"].ToObject()); + } + if (token is JArray arr && arr.Count >= 2) + { + return new Vector2(arr[0].ToObject(), arr[1].ToObject()); + } + Debug.LogWarning($"Could not parse JToken '{token}' as Vector2 using fallback. Returning Vector2.zero."); + return Vector2.zero; + } + private static Quaternion ParseJTokenToQuaternion(JToken token) + { + // ... (implementation - likely replaced by QuaternionConverter) ... + if (token is JObject obj && obj.ContainsKey("x") && obj.ContainsKey("y") && obj.ContainsKey("z") && obj.ContainsKey("w")) + { + return new Quaternion(obj["x"].ToObject(), obj["y"].ToObject(), obj["z"].ToObject(), obj["w"].ToObject()); + } + if (token is JArray arr && arr.Count >= 4) + { + return new Quaternion(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject(), arr[3].ToObject()); + } + Debug.LogWarning($"Could not parse JToken '{token}' as Quaternion using fallback. Returning Quaternion.identity."); + return Quaternion.identity; + } + private static Color ParseJTokenToColor(JToken token) + { + // ... (implementation - likely replaced by ColorConverter) ... + if (token is JObject obj && obj.ContainsKey("r") && obj.ContainsKey("g") && obj.ContainsKey("b") && obj.ContainsKey("a")) + { + return new Color(obj["r"].ToObject(), obj["g"].ToObject(), obj["b"].ToObject(), obj["a"].ToObject()); + } + if (token is JArray arr && arr.Count >= 4) + { + return new Color(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject(), arr[3].ToObject()); + } + Debug.LogWarning($"Could not parse JToken '{token}' as Color using fallback. Returning Color.white."); + return Color.white; + } + private static Rect ParseJTokenToRect(JToken token) + { + // ... (implementation - likely replaced by RectConverter) ... + if (token is JObject obj && obj.ContainsKey("x") && obj.ContainsKey("y") && obj.ContainsKey("width") && obj.ContainsKey("height")) + { + return new Rect(obj["x"].ToObject(), obj["y"].ToObject(), obj["width"].ToObject(), obj["height"].ToObject()); + } + if (token is JArray arr && arr.Count >= 4) + { + return new Rect(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject(), arr[3].ToObject()); + } + Debug.LogWarning($"Could not parse JToken '{token}' as Rect using fallback. Returning Rect.zero."); + return Rect.zero; + } + private static Bounds ParseJTokenToBounds(JToken token) + { + // ... (implementation - likely replaced by BoundsConverter) ... + if (token is JObject obj && obj.ContainsKey("center") && obj.ContainsKey("size")) + { + // Requires Vector3 conversion, which should ideally use the serializer too + Vector3 center = ParseJTokenToVector3(obj["center"]); // Or use obj["center"].ToObject(inputSerializer) + Vector3 size = ParseJTokenToVector3(obj["size"]); // Or use obj["size"].ToObject(inputSerializer) + return new Bounds(center, size); + } + // Array fallback for Bounds is less intuitive, maybe remove? + // if (token is JArray arr && arr.Count >= 6) + // { + // return new Bounds(new Vector3(arr[0].ToObject(), arr[1].ToObject(), arr[2].ToObject()), new Vector3(arr[3].ToObject(), arr[4].ToObject(), arr[5].ToObject())); + // } + Debug.LogWarning($"Could not parse JToken '{token}' as Bounds using fallback. Returning new Bounds(Vector3.zero, Vector3.zero)."); + return new Bounds(Vector3.zero, Vector3.zero); + } + // --- End Redundant Parse Helpers --- + + /// + /// Finds a specific UnityEngine.Object based on a find instruction JObject. + /// Primarily used by UnityEngineObjectConverter during deserialization. + /// + // Made public static so UnityEngineObjectConverter can call it. Moved from ConvertJTokenToType. + public static UnityEngine.Object FindObjectByInstruction(JObject instruction, Type targetType) + { + string findTerm = instruction["find"]?.ToString(); + string method = instruction["method"]?.ToString()?.ToLower(); + string componentName = instruction["component"]?.ToString(); // Specific component to get + + if (string.IsNullOrEmpty(findTerm)) + { + Debug.LogWarning("Find instruction missing 'find' term."); + return null; + } + + // Use a flexible default search method if none provided + string searchMethodToUse = string.IsNullOrEmpty(method) ? "by_id_or_name_or_path" : method; + + // If the target is an asset (Material, Texture, ScriptableObject etc.) try AssetDatabase first + if (typeof(Material).IsAssignableFrom(targetType) || + typeof(Texture).IsAssignableFrom(targetType) || + typeof(ScriptableObject).IsAssignableFrom(targetType) || + targetType.FullName.StartsWith("UnityEngine.U2D") || // Sprites etc. + typeof(AudioClip).IsAssignableFrom(targetType) || + typeof(AnimationClip).IsAssignableFrom(targetType) || + typeof(Font).IsAssignableFrom(targetType) || + typeof(Shader).IsAssignableFrom(targetType) || + typeof(ComputeShader).IsAssignableFrom(targetType) || + typeof(GameObject).IsAssignableFrom(targetType) && findTerm.StartsWith("Assets/")) // Prefab check + { + // Try loading directly by path/GUID first + UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(findTerm, targetType); + if (asset != null) return asset; + asset = AssetDatabase.LoadAssetAtPath(findTerm); // Try generic if type specific failed + if (asset != null && targetType.IsAssignableFrom(asset.GetType())) return asset; + + + // If direct path failed, try finding by name/type using FindAssets + string searchFilter = $"t:{targetType.Name} {System.IO.Path.GetFileNameWithoutExtension(findTerm)}"; // Search by type and name + string[] guids = AssetDatabase.FindAssets(searchFilter); + + if (guids.Length == 1) + { + asset = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guids[0]), targetType); + if (asset != null) return asset; + } + else if (guids.Length > 1) + { + Debug.LogWarning($"[FindObjectByInstruction] Ambiguous asset find: Found {guids.Length} assets matching filter '{searchFilter}'. Provide a full path or unique name."); + // Optionally return the first one? Or null? Returning null is safer. + return null; + } + // If still not found, fall through to scene search (though unlikely for assets) + } + + + // --- Scene Object Search --- + // Find the GameObject using the internal finder + GameObject foundGo = FindObjectInternal(new JValue(findTerm), searchMethodToUse); + + if (foundGo == null) + { + // Don't warn yet, could still be an asset not found above + // Debug.LogWarning($"Could not find GameObject using instruction: {instruction}"); + return null; + } + + // Now, get the target object/component from the found GameObject + if (targetType == typeof(GameObject)) + { + return foundGo; // We were looking for a GameObject + } + else if (typeof(Component).IsAssignableFrom(targetType)) + { + Type componentToGetType = targetType; + if (!string.IsNullOrEmpty(componentName)) + { + Type specificCompType = FindType(componentName); + if (specificCompType != null && typeof(Component).IsAssignableFrom(specificCompType)) + { + componentToGetType = specificCompType; + } + else + { + Debug.LogWarning($"Could not find component type '{componentName}' specified in find instruction. Falling back to target type '{targetType.Name}'."); + } + } + + Component foundComp = foundGo.GetComponent(componentToGetType); + if (foundComp == null) + { + Debug.LogWarning($"Found GameObject '{foundGo.name}' but could not find component of type '{componentToGetType.Name}'."); + } + return foundComp; + } + else + { + Debug.LogWarning($"Find instruction handling not implemented for target type: {targetType.Name}"); + return null; + } + } + + /// /// Helper to find a Type by name, searching relevant assemblies. /// @@ -2068,37 +1978,50 @@ namespace UnityMcpBridge.Editor.Tools if (string.IsNullOrEmpty(typeName)) return null; - // Handle common Unity namespaces implicitly - var type = - Type.GetType($"UnityEngine.{typeName}, UnityEngine.CoreModule") - ?? Type.GetType($"UnityEngine.{typeName}, UnityEngine.PhysicsModule") - ?? // Example physics - Type.GetType($"UnityEngine.UI.{typeName}, UnityEngine.UI") - ?? // Example UI - Type.GetType($"UnityEditor.{typeName}, UnityEditor.CoreModule") - ?? Type.GetType(typeName); // Try direct name (if fully qualified or in mscorlib) + // Handle fully qualified names first + Type type = Type.GetType(typeName); + if (type != null) return type; - if (type != null) - return type; + // Handle common namespaces implicitly (add more as needed) + string[] namespaces = { "UnityEngine", "UnityEngine.UI", "UnityEngine.AI", "UnityEngine.Animations", "UnityEngine.Audio", "UnityEngine.EventSystems", "UnityEngine.InputSystem", "UnityEngine.Networking", "UnityEngine.Rendering", "UnityEngine.SceneManagement", "UnityEngine.Tilemaps", "UnityEngine.U2D", "UnityEngine.Video", "UnityEditor", "UnityEditor.AI", "UnityEditor.Animations", "UnityEditor.Experimental.GraphView", "UnityEditor.IMGUI.Controls", "UnityEditor.PackageManager.UI", "UnityEditor.SceneManagement", "UnityEditor.UI", "UnityEditor.U2D", "UnityEditor.VersionControl" }; // Add more relevant namespaces - // If not found, search all loaded assemblies (slower) - foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) + foreach (string ns in namespaces) { + type = Type.GetType($"{ns}.{typeName}, {ns.Split('.')[0]}.CoreModule") ?? // Heuristic: Check CoreModule first for UnityEngine/UnityEditor + Type.GetType($"{ns}.{typeName}, {ns.Split('.')[0]}"); // Try assembly matching namespace root + if (type != null) return type; + } + + + // If not found, search all loaded assemblies (slower, last resort) + // Prioritize assemblies likely to contain game/editor types + Assembly[] priorityAssemblies = { + Assembly.Load("Assembly-CSharp"), // Main game scripts + Assembly.Load("Assembly-CSharp-Editor"), // Main editor scripts + // Add other important project assemblies if known + }; + foreach (var assembly in priorityAssemblies.Where(a => a != null)) + { + type = assembly.GetType(typeName) ?? assembly.GetType("UnityEngine." + typeName) ?? assembly.GetType("UnityEditor." + typeName); + if (type != null) return type; + } + + // Search remaining assemblies + foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies().Except(priorityAssemblies)) { - type = assembly.GetType(typeName); - if (type != null) - return type; - // Also check with namespaces if simple name given - type = assembly.GetType("UnityEngine." + typeName); - if (type != null) - return type; - type = assembly.GetType("UnityEditor." + typeName); - if (type != null) - return type; - type = assembly.GetType("UnityEngine.UI." + typeName); - if (type != null) - return type; + try { // Protect against assembly loading errors + type = assembly.GetType(typeName); + if (type != null) return type; + // Also check with common namespaces if simple name given + foreach (string ns in namespaces) { + type = assembly.GetType($"{ns}.{typeName}"); + if (type != null) return type; + } + } catch (Exception ex) { + Debug.LogWarning($"[FindType] Error searching assembly {assembly.FullName}: {ex.Message}"); + } } + Debug.LogWarning($"[FindType] Type not found after extensive search: '{typeName}'"); return null; // Not found } @@ -2111,368 +2034,23 @@ namespace UnityMcpBridge.Editor.Tools { try { + // Use ToObject for potentially better handling than direct indexing return new Vector3( array[0].ToObject(), array[1].ToObject(), array[2].ToObject() ); } - catch - { /* Ignore parsing errors */ + catch (Exception ex) + { + Debug.LogWarning($"Failed to parse JArray as Vector3: {array}. Error: {ex.Message}"); } } return null; } - // --- Data Serialization --- - - /// - /// Creates a serializable representation of a GameObject. - /// - private static object GetGameObjectData(GameObject go) - { - if (go == null) - return null; - return new - { - name = go.name, - instanceID = go.GetInstanceID(), - tag = go.tag, - layer = go.layer, - activeSelf = go.activeSelf, - activeInHierarchy = go.activeInHierarchy, - isStatic = go.isStatic, - scenePath = go.scene.path, // Identify which scene it belongs to - transform = new // Serialize transform components carefully to avoid JSON issues - { - // Serialize Vector3 components individually to prevent self-referencing loops. - // The default serializer can struggle with properties like Vector3.normalized. - position = new - { - x = go.transform.position.x, - y = go.transform.position.y, - z = go.transform.position.z, - }, - localPosition = new - { - x = go.transform.localPosition.x, - y = go.transform.localPosition.y, - z = go.transform.localPosition.z, - }, - rotation = new - { - x = go.transform.rotation.eulerAngles.x, - y = go.transform.rotation.eulerAngles.y, - z = go.transform.rotation.eulerAngles.z, - }, - localRotation = new - { - x = go.transform.localRotation.eulerAngles.x, - y = go.transform.localRotation.eulerAngles.y, - z = go.transform.localRotation.eulerAngles.z, - }, - scale = new - { - x = go.transform.localScale.x, - y = go.transform.localScale.y, - z = go.transform.localScale.z, - }, - forward = new - { - x = go.transform.forward.x, - y = go.transform.forward.y, - z = go.transform.forward.z, - }, - up = new - { - x = go.transform.up.x, - y = go.transform.up.y, - z = go.transform.up.z, - }, - right = new - { - x = go.transform.right.x, - y = go.transform.right.y, - z = go.transform.right.z, - }, - }, - parentInstanceID = go.transform.parent?.gameObject.GetInstanceID() ?? 0, // 0 if no parent - // Optionally include components, but can be large - // components = go.GetComponents().Select(c => GetComponentData(c)).ToList() - // Or just component names: - componentNames = go.GetComponents() - .Select(c => c.GetType().FullName) - .ToList(), - }; - } - - // --- Metadata Caching for Reflection --- - private class CachedMetadata - { - public readonly List SerializableProperties; - public readonly List SerializableFields; - - public CachedMetadata(List properties, List fields) - { - SerializableProperties = properties; - SerializableFields = fields; - } - } - // Key becomes Tuple - private static readonly Dictionary, CachedMetadata> _metadataCache = new Dictionary, CachedMetadata>(); - // --- End Metadata Caching --- - - /// - /// Creates a serializable representation of a Component, attempting to serialize - /// public properties and fields using reflection, with caching and control over non-public fields. - /// - // Add the flag parameter here - private static object GetComponentData(Component c, bool includeNonPublicSerializedFields = true) - { - if (c == null) return null; - Type componentType = c.GetType(); - - // TEMP: Clear cache for testing again -- REMOVING - // _metadataCache.Clear(); - - var data = new Dictionary - { - { "typeName", componentType.FullName }, - { "instanceID", c.GetInstanceID() } - }; - - // --- Get Cached or Generate Metadata (using new cache key) --- - // _metadataCache.Clear(); // TEMP: Clear cache for testing - REMOVED - Tuple cacheKey = new Tuple(componentType, includeNonPublicSerializedFields); - if (!_metadataCache.TryGetValue(cacheKey, out CachedMetadata cachedData)) - { - // ---- ADD THIS ---- - // UnityEngine.Debug.Log($"[MCP Cache Test] Metadata MISS for Type: {componentType.FullName}, IncludeNonPublic: {includeNonPublicSerializedFields}. Generating..."); - // ----------------- - var propertiesToCache = new List(); - var fieldsToCache = new List(); -//test - // Traverse the hierarchy from the component type up to MonoBehaviour - Type currentType = componentType; - while (currentType != null && currentType != typeof(MonoBehaviour) && currentType != typeof(object)) - { - // Get properties declared only at the current type level - BindingFlags propFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly; - foreach (var propInfo in currentType.GetProperties(propFlags)) - { - // Basic filtering (readable, not indexer, not transform which is handled elsewhere) - if (!propInfo.CanRead || propInfo.GetIndexParameters().Length > 0 || propInfo.Name == "transform") continue; - // Add if not already added (handles overrides - keep the most derived version) - if (!propertiesToCache.Any(p => p.Name == propInfo.Name)) { - propertiesToCache.Add(propInfo); - } - } - - // Get fields declared only at the current type level (both public and non-public) - BindingFlags fieldFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly; - var declaredFields = currentType.GetFields(fieldFlags); - - // Process the declared Fields for caching - foreach (var fieldInfo in declaredFields) - { - if (fieldInfo.Name.EndsWith("k__BackingField")) continue; // Skip backing fields - - // Add if not already added (handles hiding - keep the most derived version) - if (fieldsToCache.Any(f => f.Name == fieldInfo.Name)) continue; - - bool shouldInclude = false; - if (includeNonPublicSerializedFields) - { - // If TRUE, include Public OR NonPublic with [SerializeField] - shouldInclude = fieldInfo.IsPublic || (fieldInfo.IsPrivate && fieldInfo.IsDefined(typeof(SerializeField), inherit: false)); - } - else // includeNonPublicSerializedFields is FALSE - { - // If FALSE, include ONLY if it is explicitly Public. - shouldInclude = fieldInfo.IsPublic; - } - - if (shouldInclude) - { - fieldsToCache.Add(fieldInfo); - } - } - - // Move to the base type - currentType = currentType.BaseType; - } - // --- End Hierarchy Traversal --- - - // REMOVED Original non-hierarchical property/field gathering logic - /* - BindingFlags propFlags = BindingFlags.Public | BindingFlags.Instance; - BindingFlags fieldFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; - - foreach (var propInfo in componentType.GetProperties(propFlags)) { ... } - var allQueriedFields = componentType.GetFields(fieldFlags); - foreach (var fieldInfo in allQueriedFields) { ... } - */ - - cachedData = new CachedMetadata(propertiesToCache, fieldsToCache); - _metadataCache[cacheKey] = cachedData; // Add to cache with combined key - } - // ---- ADD THIS ---- - // UnityEngine.Debug.Log($"[MCP Cache Test] Metadata HIT for Type: {componentType.FullName}, IncludeNonPublic: {includeNonPublicSerializedFields}. Using cache."); - // ----------------- - // --- End Get Cached or Generate Metadata --- - - // --- Use cached metadata (no changes needed here) --- - var serializablePropertiesOutput = new Dictionary(); - // Use cached properties - foreach (var propInfo in cachedData.SerializableProperties) - { - // --- Skip known obsolete/problematic Component shortcut properties --- - string propName = propInfo.Name; - if (propName == "rigidbody" || propName == "rigidbody2D" || propName == "camera" || - propName == "light" || propName == "animation" || propName == "constantForce" || - propName == "renderer" || propName == "audio" || propName == "networkView" || - propName == "collider" || propName == "collider2D" || propName == "hingeJoint" || - propName == "particleSystem" || - // Also skip potentially problematic Matrix properties prone to cycles/errors - propName == "worldToLocalMatrix" || propName == "localToWorldMatrix") - { - continue; // Skip these properties - } - // --- End Skip --- - - try - { - object value = propInfo.GetValue(c); - // string propName = propInfo.Name; // Moved up - Type propType = propInfo.PropertyType; - AddSerializableValue(serializablePropertiesOutput, propName, propType, value); - } - catch (Exception ex) - { - Debug.LogWarning($"Could not read property {propName} on {componentType.Name}: {ex.Message}"); - } - } - - // Use cached fields - foreach (var fieldInfo in cachedData.SerializableFields) - { - try - { - object value = fieldInfo.GetValue(c); - string fieldName = fieldInfo.Name; - Type fieldType = fieldInfo.FieldType; - AddSerializableValue(serializablePropertiesOutput, fieldName, fieldType, value); - } - catch (Exception ex) - { - // Corrected: Use fieldInfo.Name here as fieldName is out of scope - Debug.LogWarning($"Could not read field {fieldInfo.Name} on {componentType.Name}: {ex.Message}"); - } - } - // --- End Use cached metadata --- - - if (serializablePropertiesOutput.Count > 0) - { - data["properties"] = serializablePropertiesOutput; - } - - return data; - } - - // Helper function to decide how to serialize different types - private static void AddSerializableValue(Dictionary dict, string name, Type type, object value) - { - if (value == null) - { - dict[name] = null; - return; - } - - // Primitives & Enums - if (type.IsPrimitive || type.IsEnum || type == typeof(string)) - { - dict[name] = value; - } - // Known Unity Structs (add more as needed: Rect, Bounds, etc.) - else if (type == typeof(Vector2)) { var v = (Vector2)value; dict[name] = new { v.x, v.y }; } - else if (type == typeof(Vector3)) { var v = (Vector3)value; dict[name] = new { v.x, v.y, v.z }; } - else if (type == typeof(Vector4)) { var v = (Vector4)value; dict[name] = new { v.x, v.y, v.z, v.w }; } - else if (type == typeof(Quaternion)) { var q = (Quaternion)value; dict[name] = new { x = q.eulerAngles.x, y = q.eulerAngles.y, z = q.eulerAngles.z }; } // Serialize as Euler angles for readability - else if (type == typeof(Color)) { var c = (Color)value; dict[name] = new { c.r, c.g, c.b, c.a }; } - // UnityEngine.Object References - else if (typeof(UnityEngine.Object).IsAssignableFrom(type)) - { - var obj = value as UnityEngine.Object; - if (obj != null) { - var refData = new Dictionary { - { "name", obj.name }, - { "instanceID", obj.GetInstanceID() }, - { "typeName", obj.GetType().FullName } - }; - // Attempt to get asset path and GUID -#if UNITY_EDITOR // AssetDatabase is editor-only - string assetPath = AssetDatabase.GetAssetPath(obj); - if (!string.IsNullOrEmpty(assetPath)) { - refData["assetPath"] = assetPath; - // Add GUID if asset path exists - string guid = AssetDatabase.AssetPathToGUID(assetPath); - if (!string.IsNullOrEmpty(guid)) { - refData["guid"] = guid; - } - } -#endif - dict[name] = refData; - - } else { - dict[name] = null; // The object reference is null - } - } - // Add handling for basic Lists/Arrays of primitives? (Example for List) - else if (type == typeof(List)) { - dict[name] = value as List; // Directly serializable - } - // Explicit handling for List - else if (type == typeof(List)) { - var vectorList = value as List; - if (vectorList != null) { - // Serialize each Vector3 into a list of dictionaries - var serializableList = vectorList.Select(v => new Dictionary { - { "x", v.x }, - { "y", v.y }, - { "z", v.z } - }).ToList(); - dict[name] = serializableList; - } else { - dict[name] = null; // Or an empty list, or an error message - } - } - // Attempt to serialize other complex types using JToken - else { - // UnityEngine.Debug.Log($"[MCP Debug] Attempting JToken serialization for field: {name} (Type: {type.FullName})"); // Removed this debug log - try - { - // Let Newtonsoft.Json attempt to serialize the value into a JToken - JToken jValue = JToken.FromObject(value); - // We store the JToken itself; the final JSON serialization will handle it. - // Important: Avoid potential cycles by not serializing excessively deep objects here. - // JToken.FromObject handles basic cycle detection, but complex scenarios might still occur. - // Consider adding depth limits if necessary. - dict[name] = jValue; - } - catch (JsonSerializationException jsonEx) - { - // Handle potential serialization issues (e.g., cycles, unsupported types) - Debug.LogWarning($"[AddSerializableValue] Could not serialize complex type '{type.FullName}' for property '{name}' using JToken: {jsonEx.Message}. Storing skip message."); - dict[name] = $"[Serialization Error: {type.FullName} - {jsonEx.Message}]"; - } - catch (Exception ex) - { - // Catch other unexpected errors during serialization - Debug.LogWarning($"[AddSerializableValue] Unexpected error serializing complex type '{type.FullName}' for property '{name}' using JToken: {ex.Message}"); - dict[name] = $"[Serialization Error: {type.FullName} - Unexpected]"; - } - } - } + // Removed GetGameObjectData, GetComponentData, and related private helpers/caching/serializer setup. + // They are now in Helpers.GameObjectSerializer } }