diff --git a/MCPForUnity/Editor/Helpers/ComponentOps.cs b/MCPForUnity/Editor/Helpers/ComponentOps.cs index 9a481856b..60069079a 100644 --- a/MCPForUnity/Editor/Helpers/ComponentOps.cs +++ b/MCPForUnity/Editor/Helpers/ComponentOps.cs @@ -5,6 +5,7 @@ using UnityEditor; using UnityEngine; using UnityEngine.Events; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Helpers { @@ -977,7 +978,7 @@ private static long GetSpriteFileId(Sprite sprite) } catch (Exception ex) { - McpLog.Warn($"Failed to get fileID for sprite '{sprite.name}' (instanceID={sprite.GetInstanceID()}): {ex.Message}"); + McpLog.Warn($"Failed to get fileID for sprite '{sprite.name}' (instanceID={sprite.GetInstanceIDCompat()}): {ex.Message}"); return 0; } } diff --git a/MCPForUnity/Editor/Helpers/GameObjectLookup.cs b/MCPForUnity/Editor/Helpers/GameObjectLookup.cs index a5e480f2d..1c71ea068 100644 --- a/MCPForUnity/Editor/Helpers/GameObjectLookup.cs +++ b/MCPForUnity/Editor/Helpers/GameObjectLookup.cs @@ -6,6 +6,7 @@ using UnityEditor.SceneManagement; using UnityEngine; using UnityEngine.SceneManagement; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Helpers { @@ -155,7 +156,7 @@ private static IEnumerable SearchByName(string name, bool includeInactive, if (maxResults > 0) matching = matching.Take(maxResults); - return matching.Select(go => go.GetInstanceID()); + return matching.Select(go => go.GetInstanceIDCompat()); } private static IEnumerable SearchByPath(string path, bool includeInactive) @@ -170,7 +171,7 @@ private static IEnumerable SearchByPath(string path, bool includeInactive) { if (MatchesPath(go, path)) { - yield return go.GetInstanceID(); + yield return go.GetInstanceIDCompat(); } } yield break; @@ -187,7 +188,7 @@ private static IEnumerable SearchByPath(string path, bool includeInactive) { if (MatchesPath(go, path)) { - yield return go.GetInstanceID(); + yield return go.GetInstanceIDCompat(); } } } @@ -197,7 +198,7 @@ private static IEnumerable SearchByPath(string path, bool includeInactive) var found = GameObject.Find(path); if (found != null) { - yield return found.GetInstanceID(); + yield return found.GetInstanceIDCompat(); } } } @@ -230,7 +231,7 @@ private static IEnumerable SearchByTag(string tag, bool includeInactive, in foreach (var go in results) { - yield return go.GetInstanceID(); + yield return go.GetInstanceIDCompat(); } } @@ -254,7 +255,7 @@ private static IEnumerable SearchByLayer(string layerName, bool includeInac foreach (var go in matching) { - yield return go.GetInstanceID(); + yield return go.GetInstanceIDCompat(); } } @@ -274,7 +275,7 @@ private static IEnumerable SearchByComponent(string componentTypeName, bool { if (go.GetComponent(componentType) != null) { - yield return go.GetInstanceID(); + yield return go.GetInstanceIDCompat(); count++; if (maxResults > 0 && count >= maxResults) diff --git a/MCPForUnity/Editor/Helpers/GameObjectSerializer.cs b/MCPForUnity/Editor/Helpers/GameObjectSerializer.cs index da24771d6..22b1374e9 100644 --- a/MCPForUnity/Editor/Helpers/GameObjectSerializer.cs +++ b/MCPForUnity/Editor/Helpers/GameObjectSerializer.cs @@ -7,6 +7,7 @@ using Newtonsoft.Json.Linq; using UnityEditor; using UnityEngine; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Helpers { @@ -28,7 +29,7 @@ public static object GetGameObjectData(GameObject go) return new { name = go.name, - instanceID = go.GetInstanceID(), + instanceID = go.GetInstanceIDCompat(), tag = go.tag, layer = go.layer, activeSelf = go.activeSelf, @@ -88,7 +89,7 @@ public static object GetGameObjectData(GameObject go) z = go.transform.right.z, }, }, - parentInstanceID = go.transform.parent?.gameObject.GetInstanceID() ?? 0, // 0 if no parent + parentInstanceID = go.transform.parent?.gameObject.GetInstanceIDCompat() ?? 0, // 0 if no parent // Optionally include components, but can be large // components = go.GetComponents().Select(c => GetComponentData(c)).ToList() // Or just component names: @@ -144,7 +145,7 @@ private static Dictionary SerializeAssetReference(UnityEngine.Ob var result = new Dictionary { { "name", obj.name }, - { "instanceID", obj.GetInstanceID() } + { "instanceID", obj.GetInstanceIDCompat() } }; if (includeAssetPath) @@ -164,7 +165,7 @@ private static Dictionary SerializeAssetReference(UnityEngine.Ob public static object GetComponentData(Component c, bool includeNonPublicSerializedFields = true) { // --- Add Early Logging --- - // McpLog.Info($"[GetComponentData] Starting for component: {c?.GetType()?.FullName ?? "null"} (ID: {c?.GetInstanceID() ?? 0})"); + // McpLog.Info($"[GetComponentData] Starting for component: {c?.GetType()?.FullName ?? "null"} (ID: {c?.GetInstanceIDCompat() ?? 0})"); // --- End Early Logging --- if (c == null) return null; @@ -174,11 +175,11 @@ public static object GetComponentData(Component c, bool includeNonPublicSerializ if (componentType == typeof(Transform)) { Transform tr = c as Transform; - // McpLog.Info($"[GetComponentData] Manually serializing Transform (ID: {tr.GetInstanceID()})"); + // McpLog.Info($"[GetComponentData] Manually serializing Transform (ID: {tr.GetInstanceIDCompat()})"); return new Dictionary { { "typeName", componentType.FullName }, - { "instanceID", tr.GetInstanceID() }, + { "instanceID", tr.GetInstanceIDCompat() }, // Manually extract known-safe properties. Avoid Quaternion 'rotation' and 'lossyScale'. { "position", CreateTokenFromValue(tr.position, typeof(Vector3))?.ToObject() ?? new JObject() }, { "localPosition", CreateTokenFromValue(tr.localPosition, typeof(Vector3))?.ToObject() ?? new JObject() }, @@ -188,13 +189,13 @@ public static object GetComponentData(Component c, bool includeNonPublicSerializ { "right", CreateTokenFromValue(tr.right, typeof(Vector3))?.ToObject() ?? new JObject() }, { "up", CreateTokenFromValue(tr.up, typeof(Vector3))?.ToObject() ?? new JObject() }, { "forward", CreateTokenFromValue(tr.forward, typeof(Vector3))?.ToObject() ?? new JObject() }, - { "parentInstanceID", tr.parent?.gameObject.GetInstanceID() ?? 0 }, - { "rootInstanceID", tr.root?.gameObject.GetInstanceID() ?? 0 }, + { "parentInstanceID", tr.parent?.gameObject.GetInstanceIDCompat() ?? 0 }, + { "rootInstanceID", tr.root?.gameObject.GetInstanceIDCompat() ?? 0 }, { "childCount", tr.childCount }, // Include standard Object/Component properties { "name", tr.name }, { "tag", tr.tag }, - { "gameObjectInstanceID", tr.gameObject?.GetInstanceID() ?? 0 } + { "gameObjectInstanceID", tr.gameObject?.GetInstanceIDCompat() ?? 0 } }; } // --- End Special handling for Transform --- @@ -233,7 +234,7 @@ public static object GetComponentData(Component c, bool includeNonPublicSerializ { "enabled", () => cam.enabled }, { "name", () => cam.name }, { "tag", () => cam.tag }, - { "gameObject", () => new { name = cam.gameObject.name, instanceID = cam.gameObject.GetInstanceID() } } + { "gameObject", () => new { name = cam.gameObject.name, instanceID = cam.gameObject.GetInstanceIDCompat() } } }; foreach (var prop in safeProperties) @@ -256,7 +257,7 @@ public static object GetComponentData(Component c, bool includeNonPublicSerializ return new Dictionary { { "typeName", componentType.FullName }, - { "instanceID", cam.GetInstanceID() }, + { "instanceID", cam.GetInstanceIDCompat() }, { "properties", cameraProperties } }; } @@ -322,7 +323,7 @@ public static object GetComponentData(Component c, bool includeNonPublicSerializ return new Dictionary { { "typeName", componentType.FullName }, - { "instanceID", c.GetInstanceID() }, + { "instanceID", c.GetInstanceIDCompat() }, { "properties", uiDocProperties } }; } @@ -331,7 +332,7 @@ public static object GetComponentData(Component c, bool includeNonPublicSerializ var data = new Dictionary { { "typeName", componentType.FullName }, - { "instanceID", c.GetInstanceID() } + { "instanceID", c.GetInstanceIDCompat() } }; // --- Get Cached or Generate Metadata (using new cache key) --- diff --git a/MCPForUnity/Editor/Resources/Editor/Selection.cs b/MCPForUnity/Editor/Resources/Editor/Selection.cs index 406b9c8f8..8cf4ef957 100644 --- a/MCPForUnity/Editor/Resources/Editor/Selection.cs +++ b/MCPForUnity/Editor/Resources/Editor/Selection.cs @@ -3,6 +3,7 @@ using MCPForUnity.Editor.Helpers; using Newtonsoft.Json.Linq; using UnityEditor; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Resources.Editor { @@ -21,21 +22,21 @@ public static object HandleCommand(JObject @params) activeObject = UnityEditor.Selection.activeObject?.name, activeGameObject = UnityEditor.Selection.activeGameObject?.name, activeTransform = UnityEditor.Selection.activeTransform?.name, - activeInstanceID = UnityEditor.Selection.activeObject?.GetInstanceID() ?? 0, + activeInstanceID = UnityEditor.Selection.activeObject?.GetInstanceIDCompat() ?? 0, count = UnityEditor.Selection.count, objects = UnityEditor.Selection.objects .Select(obj => new { name = obj?.name, type = obj?.GetType().FullName, - instanceID = obj?.GetInstanceID() + instanceID = obj?.GetInstanceIDCompat() }) .ToList(), gameObjects = UnityEditor.Selection.gameObjects .Select(go => new { name = go?.name, - instanceID = go?.GetInstanceID() + instanceID = go?.GetInstanceIDCompat() }) .ToList(), assetGUIDs = UnityEditor.Selection.assetGUIDs diff --git a/MCPForUnity/Editor/Resources/Editor/Windows.cs b/MCPForUnity/Editor/Resources/Editor/Windows.cs index b69a9d313..675dd3b93 100644 --- a/MCPForUnity/Editor/Resources/Editor/Windows.cs +++ b/MCPForUnity/Editor/Resources/Editor/Windows.cs @@ -4,6 +4,7 @@ using Newtonsoft.Json.Linq; using UnityEditor; using UnityEngine; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Resources.Editor { @@ -39,7 +40,7 @@ public static object HandleCommand(JObject @params) width = window.position.width, height = window.position.height }, - instanceID = window.GetInstanceID() + instanceID = window.GetInstanceIDCompat() }); } catch (Exception ex) diff --git a/MCPForUnity/Editor/Resources/Scene/GameObjectResource.cs b/MCPForUnity/Editor/Resources/Scene/GameObjectResource.cs index 40f41a486..a5f511859 100644 --- a/MCPForUnity/Editor/Resources/Scene/GameObjectResource.cs +++ b/MCPForUnity/Editor/Resources/Scene/GameObjectResource.cs @@ -5,6 +5,7 @@ using Newtonsoft.Json.Linq; using UnityEditor; using UnityEngine; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Resources.Scene { @@ -84,12 +85,12 @@ public static object SerializeGameObject(GameObject go) var childrenIds = new List(); foreach (Transform child in transform) { - childrenIds.Add(child.gameObject.GetInstanceID()); + childrenIds.Add(child.gameObject.GetInstanceIDCompat()); } return new { - instanceID = go.GetInstanceID(), + instanceID = go.GetInstanceIDCompat(), name = go.name, tag = go.tag, layer = go.layer, @@ -106,7 +107,7 @@ public static object SerializeGameObject(GameObject go) scale = SerializeVector3(transform.localScale), lossyScale = SerializeVector3(transform.lossyScale) }, - parent = transform.parent != null ? transform.parent.gameObject.GetInstanceID() : (int?)null, + parent = transform.parent != null ? transform.parent.gameObject.GetInstanceIDCompat() : (int?)null, children = childrenIds, componentTypes = componentTypes, path = GameObjectLookup.GetGameObjectPath(go) @@ -173,7 +174,7 @@ public static object HandleCommand(JObject @params) componentData.Add(new { typeName = component.GetType().FullName, - instanceID = component.GetInstanceID() + instanceID = component.GetInstanceIDCompat() }); } } diff --git a/MCPForUnity/Editor/Tools/Cameras/CameraConfigure.cs b/MCPForUnity/Editor/Tools/Cameras/CameraConfigure.cs index 214be1e85..6bfaffd3c 100644 --- a/MCPForUnity/Editor/Tools/Cameras/CameraConfigure.cs +++ b/MCPForUnity/Editor/Tools/Cameras/CameraConfigure.cs @@ -4,6 +4,7 @@ using Newtonsoft.Json.Linq; using UnityEditor; using UnityEngine; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Tools.Cameras { @@ -36,7 +37,7 @@ internal static object SetBasicCameraTarget(JObject @params) { success = true, message = $"Camera '{go.name}' now looking at '{target.name}'.", - data = new { instanceID = go.GetInstanceID() } + data = new { instanceID = go.GetInstanceIDCompat() } }; } @@ -65,7 +66,7 @@ internal static object SetBasicCameraLens(JObject @params) { success = true, message = $"Lens properties set on Camera '{go.name}'.", - data = new { instanceID = go.GetInstanceID() } + data = new { instanceID = go.GetInstanceIDCompat() } }; } @@ -88,7 +89,7 @@ internal static object SetBasicCameraPriority(JObject @params) { success = true, message = $"Camera '{go.name}' depth set to {depth}.", - data = new { instanceID = go.GetInstanceID(), depth } + data = new { instanceID = go.GetInstanceIDCompat(), depth } }; } @@ -116,7 +117,7 @@ internal static object SetCinemachineTarget(JObject @params) { success = true, message = $"Targets set on CinemachineCamera '{cmCamera.gameObject.name}'.", - data = new { instanceID = cmCamera.gameObject.GetInstanceID() } + data = new { instanceID = cmCamera.gameObject.GetInstanceIDCompat() } }; } @@ -147,7 +148,7 @@ internal static object SetCinemachineLens(JObject @params) { success = true, message = $"Lens properties set on CinemachineCamera '{cmCamera.gameObject.name}'.", - data = new { instanceID = cmCamera.gameObject.GetInstanceID() } + data = new { instanceID = cmCamera.gameObject.GetInstanceIDCompat() } }; } @@ -181,7 +182,7 @@ internal static object SetCinemachinePriority(JObject @params) { success = true, message = $"Priority set to {priority} on CinemachineCamera '{cmCamera.gameObject.name}'.", - data = new { instanceID = cmCamera.gameObject.GetInstanceID(), priority } + data = new { instanceID = cmCamera.gameObject.GetInstanceIDCompat(), priority } }; } @@ -218,7 +219,7 @@ internal static object SetBody(JObject @params) { success = true, message = $"Body configured on CinemachineCamera '{go.name}'.", - data = new { instanceID = go.GetInstanceID(), body = bodyComponent.GetType().Name } + data = new { instanceID = go.GetInstanceIDCompat(), body = bodyComponent.GetType().Name } }; } @@ -253,7 +254,7 @@ internal static object SetAim(JObject @params) { success = true, message = $"Aim configured on CinemachineCamera '{go.name}'.", - data = new { instanceID = go.GetInstanceID(), aim = aimComponent.GetType().Name } + data = new { instanceID = go.GetInstanceIDCompat(), aim = aimComponent.GetType().Name } }; } @@ -288,7 +289,7 @@ internal static object SetNoise(JObject @params) message = added ? $"Added noise to CinemachineCamera '{go.name}'." : $"Noise configured on CinemachineCamera '{go.name}'.", - data = new { instanceID = go.GetInstanceID(), added } + data = new { instanceID = go.GetInstanceIDCompat(), added } }; } @@ -320,7 +321,7 @@ internal static object AddExtension(JObject @params) { success = true, message = $"Extension '{extTypeName}' added to CinemachineCamera '{go.name}'.", - data = new { instanceID = go.GetInstanceID(), extensionType = extTypeName } + data = new { instanceID = go.GetInstanceIDCompat(), extensionType = extTypeName } }; } @@ -351,7 +352,7 @@ internal static object RemoveExtension(JObject @params) { success = true, message = $"Extension '{extTypeName}' removed from CinemachineCamera '{go.name}'.", - data = new { instanceID = go.GetInstanceID() } + data = new { instanceID = go.GetInstanceIDCompat() } }; } diff --git a/MCPForUnity/Editor/Tools/Cameras/CameraControl.cs b/MCPForUnity/Editor/Tools/Cameras/CameraControl.cs index 982807f70..ea676a67f 100644 --- a/MCPForUnity/Editor/Tools/Cameras/CameraControl.cs +++ b/MCPForUnity/Editor/Tools/Cameras/CameraControl.cs @@ -6,6 +6,7 @@ using Newtonsoft.Json.Linq; using UnityEditor; using UnityEngine; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Tools.Cameras { @@ -13,11 +14,7 @@ internal static class CameraControl { internal static object ListCameras(JObject @params) { -#if UNITY_2022_2_OR_NEWER - var unityCameras = UnityEngine.Object.FindObjectsByType(FindObjectsSortMode.None); -#else - var unityCameras = UnityEngine.Object.FindObjectsOfType(); -#endif + var unityCameras = UnityFindObjectsCompat.FindAll(); var cameraList = new List(); var unityCamList = new List(); @@ -25,11 +22,7 @@ internal static object ListCameras(JObject @params) if (CameraHelpers.HasCinemachine) { var cmType = CameraHelpers.CinemachineCameraType; -#if UNITY_2022_2_OR_NEWER - var allCm = UnityEngine.Object.FindObjectsByType(cmType, FindObjectsSortMode.None); -#else - var allCm = UnityEngine.Object.FindObjectsOfType(cmType); -#endif + var allCm = UnityFindObjectsCompat.FindAll(cmType); foreach (Component cm in allCm) { var follow = CameraHelpers.GetReflectionProperty(cm, "Follow") as Transform; @@ -55,12 +48,12 @@ internal static object ListCameras(JObject @params) cameraList.Add(new { - instanceID = cm.gameObject.GetInstanceID(), + instanceID = cm.gameObject.GetInstanceIDCompat(), name = cm.gameObject.name, isLive = isLive is bool b && b, priority, - follow = follow != null ? new { name = follow.gameObject.name, instanceID = follow.gameObject.GetInstanceID() } : null, - lookAt = lookAt != null ? new { name = lookAt.gameObject.name, instanceID = lookAt.gameObject.GetInstanceID() } : null, + follow = follow != null ? new { name = follow.gameObject.name, instanceID = follow.gameObject.GetInstanceIDCompat() } : null, + lookAt = lookAt != null ? new { name = lookAt.gameObject.name, instanceID = lookAt.gameObject.GetInstanceIDCompat() } : null, body = body?.GetType().Name, aim = aim?.GetType().Name, noise = noise?.GetType().Name, @@ -76,7 +69,7 @@ internal static object ListCameras(JObject @params) cam.gameObject.GetComponent(CameraHelpers.CinemachineBrainType) != null; unityCamList.Add(new { - instanceID = cam.gameObject.GetInstanceID(), + instanceID = cam.gameObject.GetInstanceIDCompat(), name = cam.gameObject.name, depth = cam.depth, fieldOfView = cam.fieldOfView, @@ -102,14 +95,14 @@ internal static object ListCameras(JObject @params) activeName = nameProp?.GetValue(activeCam) as string; if (activeCam is Component activeComp) - activeID = activeComp.gameObject.GetInstanceID(); + activeID = activeComp.gameObject.GetInstanceIDCompat(); } brainInfo = new { exists = true, gameObject = brain.gameObject.name, - instanceID = brain.gameObject.GetInstanceID(), + instanceID = brain.gameObject.GetInstanceIDCompat(), activeCameraName = activeName, activeCameraID = activeID, isBlending = isBlending is bool bl && bl @@ -147,7 +140,7 @@ internal static object GetBrainStatus(JObject @params) var nameProp = activeCam.GetType().GetProperty("Name"); activeName = nameProp?.GetValue(activeCam) as string; if (activeCam is Component comp) - activeID = comp.gameObject.GetInstanceID(); + activeID = comp.gameObject.GetInstanceIDCompat(); } string blendDesc = null; @@ -163,7 +156,7 @@ internal static object GetBrainStatus(JObject @params) data = new { gameObject = brain.gameObject.name, - instanceID = brain.gameObject.GetInstanceID(), + instanceID = brain.gameObject.GetInstanceIDCompat(), activeCameraName = activeName, activeCameraID = activeID, isBlending = isBlending is bool b && b, @@ -217,7 +210,7 @@ internal static object SetBlend(JObject @params) { success = true, message = "Default blend configured on CinemachineBrain.", - data = new { instanceID = brain.gameObject.GetInstanceID() } + data = new { instanceID = brain.gameObject.GetInstanceIDCompat() } }; } @@ -246,7 +239,7 @@ internal static object ForceCamera(JObject @params) { success = true, message = $"Set high priority on '{cmCamera.gameObject.name}' (SetCameraOverride not available).", - data = new { instanceID = cmCamera.gameObject.GetInstanceID(), method = "priority" } + data = new { instanceID = cmCamera.gameObject.GetInstanceIDCompat(), method = "priority" } }; } @@ -273,7 +266,7 @@ internal static object ForceCamera(JObject @params) { success = true, message = $"Forced via priority (override failed: {ex.Message}).", - data = new { instanceID = cmCamera.gameObject.GetInstanceID(), method = "priority" } + data = new { instanceID = cmCamera.gameObject.GetInstanceIDCompat(), method = "priority" } }; } @@ -283,7 +276,7 @@ internal static object ForceCamera(JObject @params) message = $"Camera overridden to '{cmCamera.gameObject.name}'.", data = new { - instanceID = cmCamera.gameObject.GetInstanceID(), + instanceID = cmCamera.gameObject.GetInstanceIDCompat(), overrideId = _overrideId, method = "override" } diff --git a/MCPForUnity/Editor/Tools/Cameras/CameraCreate.cs b/MCPForUnity/Editor/Tools/Cameras/CameraCreate.cs index b33668bd2..d01e2ca84 100644 --- a/MCPForUnity/Editor/Tools/Cameras/CameraCreate.cs +++ b/MCPForUnity/Editor/Tools/Cameras/CameraCreate.cs @@ -5,6 +5,7 @@ using Newtonsoft.Json.Linq; using UnityEditor; using UnityEngine; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Tools.Cameras { @@ -62,7 +63,7 @@ internal static object CreateBasicCamera(JObject @params) message = $"Created basic Camera '{name}' (Cinemachine not installed — using Unity Camera).", data = new { - instanceID = go.GetInstanceID(), + instanceID = go.GetInstanceIDCompat(), cinemachine = false, hint = "Install com.unity.cinemachine for presets, blending, and virtual camera features." } @@ -149,7 +150,7 @@ internal static object CreateCinemachineCamera(JObject @params) message = $"Created CinemachineCamera '{name}' with preset '{preset}'.", data = new { - instanceID = go.GetInstanceID(), + instanceID = go.GetInstanceIDCompat(), cinemachine = true, preset, priority, @@ -173,7 +174,7 @@ internal static object EnsureBrain(JObject @params) message = $"CinemachineBrain already exists on '{existingBrain.gameObject.name}'.", data = new { - instanceID = existingBrain.gameObject.GetInstanceID(), + instanceID = existingBrain.gameObject.GetInstanceIDCompat(), alreadyExisted = true } }; @@ -241,7 +242,7 @@ internal static object EnsureBrain(JObject @params) message = $"CinemachineBrain added to '{cam.gameObject.name}'.", data = new { - instanceID = cam.gameObject.GetInstanceID(), + instanceID = cam.gameObject.GetInstanceIDCompat(), alreadyExisted = false } }; diff --git a/MCPForUnity/Editor/Tools/Cameras/CameraHelpers.cs b/MCPForUnity/Editor/Tools/Cameras/CameraHelpers.cs index 5ca870e55..80e75a3bb 100644 --- a/MCPForUnity/Editor/Tools/Cameras/CameraHelpers.cs +++ b/MCPForUnity/Editor/Tools/Cameras/CameraHelpers.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Reflection; using MCPForUnity.Editor.Helpers; +using MCPForUnity.Runtime.Helpers; using Newtonsoft.Json.Linq; using UnityEditor; using UnityEngine; @@ -141,11 +142,7 @@ internal static Component FindBrain() if (!HasCinemachine || _cmBrainType == null) return null; -#if UNITY_2022_2_OR_NEWER - return UnityEngine.Object.FindFirstObjectByType(_cmBrainType) as Component; -#else - return UnityEngine.Object.FindObjectOfType(_cmBrainType) as Component; -#endif + return UnityFindObjectsCompat.FindAny(_cmBrainType) as Component; } internal static UnityEngine.Camera FindMainCamera() @@ -153,11 +150,7 @@ internal static UnityEngine.Camera FindMainCamera() var main = UnityEngine.Camera.main; if (main != null) return main; -#if UNITY_2022_2_OR_NEWER - var allCams = UnityEngine.Object.FindObjectsByType(FindObjectsSortMode.None); -#else - var allCams = UnityEngine.Object.FindObjectsOfType(); -#endif + var allCams = UnityFindObjectsCompat.FindAll(); return allCams.Length > 0 ? allCams[0] : null; } diff --git a/MCPForUnity/Editor/Tools/GameObjects/GameObjectDelete.cs b/MCPForUnity/Editor/Tools/GameObjects/GameObjectDelete.cs index f5681858c..74382ef49 100644 --- a/MCPForUnity/Editor/Tools/GameObjects/GameObjectDelete.cs +++ b/MCPForUnity/Editor/Tools/GameObjects/GameObjectDelete.cs @@ -4,6 +4,7 @@ using Newtonsoft.Json.Linq; using UnityEditor; using UnityEngine; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Tools.GameObjects { @@ -24,7 +25,7 @@ internal static object Handle(JToken targetToken, string searchMethod) if (targetGo != null) { string goName = targetGo.name; - int goId = targetGo.GetInstanceID(); + int goId = targetGo.GetInstanceIDCompat(); // Note: Undo.DestroyObjectImmediate doesn't work reliably in test context, // so we use Object.DestroyImmediate. This means delete isn't undoable. // TODO: Investigate Undo.DestroyObjectImmediate behavior in Unity 2022+ diff --git a/MCPForUnity/Editor/Tools/GameObjects/GameObjectDuplicate.cs b/MCPForUnity/Editor/Tools/GameObjects/GameObjectDuplicate.cs index 6faeb2ad4..414c56b94 100644 --- a/MCPForUnity/Editor/Tools/GameObjects/GameObjectDuplicate.cs +++ b/MCPForUnity/Editor/Tools/GameObjects/GameObjectDuplicate.cs @@ -4,6 +4,7 @@ using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Tools.GameObjects { @@ -77,7 +78,7 @@ internal static object Handle(JObject @params, JToken targetToken, string search new { originalName = sourceGo.name, - originalId = sourceGo.GetInstanceID(), + originalId = sourceGo.GetInstanceIDCompat(), duplicatedObject = Helpers.GameObjectSerializer.GetGameObjectData(duplicatedGo) } ); diff --git a/MCPForUnity/Editor/Tools/GameObjects/GameObjectLookAt.cs b/MCPForUnity/Editor/Tools/GameObjects/GameObjectLookAt.cs index bfeb9c13d..e30260e72 100644 --- a/MCPForUnity/Editor/Tools/GameObjects/GameObjectLookAt.cs +++ b/MCPForUnity/Editor/Tools/GameObjects/GameObjectLookAt.cs @@ -3,6 +3,7 @@ using Newtonsoft.Json.Linq; using UnityEditor; using UnityEngine; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Tools.GameObjects { @@ -53,7 +54,7 @@ internal static object Handle(JObject @params, JToken targetToken, string search new { name = targetGo.name, - instanceID = targetGo.GetInstanceID(), + instanceID = targetGo.GetInstanceIDCompat(), rotation = new[] { euler.x, euler.y, euler.z }, lookAtPosition = new[] { lookAtPos.Value.x, lookAtPos.Value.y, lookAtPos.Value.z }, } diff --git a/MCPForUnity/Editor/Tools/GameObjects/ManageGameObjectCommon.cs b/MCPForUnity/Editor/Tools/GameObjects/ManageGameObjectCommon.cs index 8d8a36eac..7afa27510 100644 --- a/MCPForUnity/Editor/Tools/GameObjects/ManageGameObjectCommon.cs +++ b/MCPForUnity/Editor/Tools/GameObjects/ManageGameObjectCommon.cs @@ -8,6 +8,7 @@ using UnityEditor.SceneManagement; using UnityEngine; using UnityEngine.SceneManagement; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Tools.GameObjects { @@ -68,7 +69,7 @@ internal static List FindObjectsInternal( if (int.TryParse(searchTerm, out int instanceId)) { var allObjects = GetAllSceneObjects(searchInactive); - GameObject obj = allObjects.FirstOrDefault(go => go.GetInstanceID() == instanceId); + GameObject obj = allObjects.FirstOrDefault(go => go.GetInstanceIDCompat() == instanceId); if (obj != null) results.Add(obj); } @@ -154,16 +155,9 @@ internal static List FindObjectsInternal( } else { -#if UNITY_2023_1_OR_NEWER - var inactive = searchInactive ? FindObjectsInactive.Include : FindObjectsInactive.Exclude; - searchPoolComp = UnityEngine.Object.FindObjectsByType(componentType, inactive, FindObjectsSortMode.None) + searchPoolComp = UnityFindObjectsCompat.FindAll(componentType, searchInactive) .Cast() .Select(c => c.gameObject); -#else - searchPoolComp = UnityEngine.Object.FindObjectsOfType(componentType, searchInactive) - .Cast() - .Select(c => c.gameObject); -#endif } results.AddRange(searchPoolComp.Where(go => go != null)); } @@ -177,7 +171,7 @@ internal static List FindObjectsInternal( if (int.TryParse(searchTerm, out int id)) { var allObjectsId = GetAllSceneObjects(true); - GameObject objById = allObjectsId.FirstOrDefault(go => go.GetInstanceID() == id); + GameObject objById = allObjectsId.FirstOrDefault(go => go.GetInstanceIDCompat() == id); if (objById != null) { results.Add(objById); diff --git a/MCPForUnity/Editor/Tools/Graphics/GraphicsHelpers.cs b/MCPForUnity/Editor/Tools/Graphics/GraphicsHelpers.cs index dcb1ef346..c410c32f0 100644 --- a/MCPForUnity/Editor/Tools/Graphics/GraphicsHelpers.cs +++ b/MCPForUnity/Editor/Tools/Graphics/GraphicsHelpers.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Reflection; using MCPForUnity.Editor.Helpers; +using MCPForUnity.Runtime.Helpers; using Newtonsoft.Json.Linq; using UnityEditor; using UnityEngine; @@ -109,11 +110,7 @@ internal static Component FindVolume(JObject @params) string target = p.Get("target"); if (string.IsNullOrEmpty(target)) { -#if UNITY_2022_2_OR_NEWER - var allVolumes = UnityEngine.Object.FindObjectsByType(VolumeType, FindObjectsSortMode.None); -#else - var allVolumes = UnityEngine.Object.FindObjectsOfType(VolumeType); -#endif + var allVolumes = UnityFindObjectsCompat.FindAll(VolumeType); return allVolumes.Length > 0 ? allVolumes[0] as Component : null; } diff --git a/MCPForUnity/Editor/Tools/Graphics/LightBakingOps.cs b/MCPForUnity/Editor/Tools/Graphics/LightBakingOps.cs index 9d8241d25..b2f904421 100644 --- a/MCPForUnity/Editor/Tools/Graphics/LightBakingOps.cs +++ b/MCPForUnity/Editor/Tools/Graphics/LightBakingOps.cs @@ -7,6 +7,7 @@ using UnityEditor; using UnityEngine; using UnityEngine.Rendering; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Tools.Graphics { @@ -124,7 +125,7 @@ internal static object BakeReflectionProbe(JObject @params) { probeName = probe.name, outputPath, - instanceID = go.GetInstanceID() + instanceID = go.GetInstanceIDCompat() } }; } @@ -274,7 +275,7 @@ internal static object CreateLightProbeGroup(JObject @params) message = $"Created Light Probe Group '{name}' with {positions.Count} probes ({gridX}x{gridY}x{gridZ} grid, spacing {spacing}).", data = new { - instanceID = go.GetInstanceID(), + instanceID = go.GetInstanceIDCompat(), probeCount = positions.Count, gridSize = new[] { gridX, gridY, gridZ }, spacing, @@ -327,7 +328,7 @@ internal static object CreateReflectionProbe(JObject @params) message = $"Created Reflection Probe '{name}' (mode: {mode}, resolution: {resolution}, HDR: {hdr}).", data = new { - instanceID = go.GetInstanceID(), + instanceID = go.GetInstanceIDCompat(), mode = mode.ToString(), resolution, hdr, @@ -383,7 +384,7 @@ internal static object SetProbePositions(JObject @params) message = $"Set {positions.Length} probe positions on '{go.name}'.", data = new { - instanceID = go.GetInstanceID(), + instanceID = go.GetInstanceIDCompat(), probeCount = positions.Length } }; diff --git a/MCPForUnity/Editor/Tools/Graphics/RendererFeatureOps.cs b/MCPForUnity/Editor/Tools/Graphics/RendererFeatureOps.cs index 5da66af18..2bd4022f2 100644 --- a/MCPForUnity/Editor/Tools/Graphics/RendererFeatureOps.cs +++ b/MCPForUnity/Editor/Tools/Graphics/RendererFeatureOps.cs @@ -7,6 +7,7 @@ using UnityEditor; using UnityEngine; using UnityEngine.Rendering; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Tools.Graphics { @@ -162,7 +163,7 @@ internal static object AddFeature(JObject @params) { name = displayName, type = featureType.Name, - instanceId = feature.GetInstanceID() + instanceId = feature.GetInstanceIDCompat() } }; } diff --git a/MCPForUnity/Editor/Tools/Graphics/SkyboxOps.cs b/MCPForUnity/Editor/Tools/Graphics/SkyboxOps.cs index ec681e448..5882505d4 100644 --- a/MCPForUnity/Editor/Tools/Graphics/SkyboxOps.cs +++ b/MCPForUnity/Editor/Tools/Graphics/SkyboxOps.cs @@ -5,6 +5,7 @@ using UnityEditor; using UnityEngine; using UnityEngine.Rendering; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Tools.Graphics { @@ -91,7 +92,7 @@ public static object GetEnvironment(JObject @params) : null }, sun = sun != null - ? (object)new { name = sun.gameObject.name, instanceID = sun.gameObject.GetInstanceID() } + ? (object)new { name = sun.gameObject.name, instanceID = sun.gameObject.GetInstanceIDCompat() } : null, subtractiveShadowColor = ColorToArray(RenderSettings.subtractiveShadowColor) } @@ -373,7 +374,7 @@ public static object SetSun(JObject @params) data = new { name = go.name, - instanceID = go.GetInstanceID(), + instanceID = go.GetInstanceIDCompat(), lightType = light.type.ToString() } }; diff --git a/MCPForUnity/Editor/Tools/Graphics/VolumeOps.cs b/MCPForUnity/Editor/Tools/Graphics/VolumeOps.cs index 4bfceffb4..69375f09a 100644 --- a/MCPForUnity/Editor/Tools/Graphics/VolumeOps.cs +++ b/MCPForUnity/Editor/Tools/Graphics/VolumeOps.cs @@ -6,6 +6,7 @@ using Newtonsoft.Json.Linq; using UnityEditor; using UnityEngine; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Tools.Graphics { @@ -124,7 +125,7 @@ internal static object CreateVolume(JObject @params) (addedEffects.Count > 0 ? $" with effects: {string.Join(", ", addedEffects)}" : ""), data = new { - instanceID = go.GetInstanceID(), + instanceID = go.GetInstanceIDCompat(), isGlobal, weight, priority, @@ -189,7 +190,7 @@ internal static object AddEffect(JObject @params) { success = true, message = $"Added '{effectName}' to Volume '{(volume as Component)?.gameObject.name}'.", - data = new { effect = effectName, volumeInstanceID = (volume as Component)?.gameObject.GetInstanceID() } + data = new { effect = effectName, volumeInstanceID = (volume as Component)?.gameObject.GetInstanceIDCompat() } }; } @@ -454,11 +455,7 @@ internal static object ListVolumes(JObject @params) if (!GraphicsHelpers.HasVolumeSystem) return new { success = true, message = "Volume system not available.", data = new { volumes = new List() } }; -#if UNITY_2022_2_OR_NEWER - var allVolumes = UnityEngine.Object.FindObjectsByType(GraphicsHelpers.VolumeType, FindObjectsSortMode.None); -#else - var allVolumes = UnityEngine.Object.FindObjectsOfType(GraphicsHelpers.VolumeType); -#endif + var allVolumes = UnityFindObjectsCompat.FindAll(GraphicsHelpers.VolumeType); var volumeList = new List(); foreach (Component vol in allVolumes) @@ -529,7 +526,7 @@ private static object BuildVolumeInfo(object volumeComponent) return new { name = comp.gameObject.name, - instance_id = comp.gameObject.GetInstanceID(), + instance_id = comp.gameObject.GetInstanceIDCompat(), is_global = isGlobal, weight, priority, diff --git a/MCPForUnity/Editor/Tools/ManageAsset.cs b/MCPForUnity/Editor/Tools/ManageAsset.cs index 1410c77c8..69aaf53cc 100644 --- a/MCPForUnity/Editor/Tools/ManageAsset.cs +++ b/MCPForUnity/Editor/Tools/ManageAsset.cs @@ -8,10 +8,11 @@ using UnityEngine; using MCPForUnity.Editor.Helpers; // For Response class using MCPForUnity.Editor.Tools; +using MCPForUnity.Runtime.Helpers; #if UNITY_6000_0_OR_NEWER using PhysicsMaterialType = UnityEngine.PhysicsMaterial; -using PhysicsMaterialCombine = UnityEngine.PhysicsMaterialCombine; +using PhysicsMaterialCombine = UnityEngine.PhysicsMaterialCombine; #else using PhysicsMaterialType = UnityEngine.PhysicMaterial; using PhysicsMaterialCombine = UnityEngine.PhysicMaterialCombine; @@ -802,7 +803,7 @@ private static object GetComponentsFromAsset(string path) .Select(comp => new { typeName = comp.GetType().FullName, - instanceID = comp.GetInstanceID(), + instanceID = comp.GetInstanceIDCompat(), // TODO: Add more component-specific details here if needed in the future? // Requires reflection or specific handling per component type. }) @@ -1104,7 +1105,7 @@ private static object GetAssetData(string path, bool generatePreview = false) name = Path.GetFileNameWithoutExtension(path), fileName = Path.GetFileName(path), isFolder = AssetDatabase.IsValidFolder(path), - instanceID = asset?.GetInstanceID() ?? 0, + instanceID = asset?.GetInstanceIDCompat() ?? 0, lastWriteTimeUtc = File.GetLastWriteTimeUtc( Path.Combine(Directory.GetCurrentDirectory(), path) ) diff --git a/MCPForUnity/Editor/Tools/ManageComponents.cs b/MCPForUnity/Editor/Tools/ManageComponents.cs index 159ce3068..0cb6757b9 100644 --- a/MCPForUnity/Editor/Tools/ManageComponents.cs +++ b/MCPForUnity/Editor/Tools/ManageComponents.cs @@ -7,6 +7,7 @@ using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Tools { @@ -118,9 +119,9 @@ private static object AddComponent(JObject @params, JToken targetToken, string s message = $"Component '{componentTypeName}' added to '{targetGo.name}'.", data = new { - instanceID = targetGo.GetInstanceID(), + instanceID = targetGo.GetInstanceIDCompat(), componentType = type.FullName, - componentInstanceID = newComponent.GetInstanceID() + componentInstanceID = newComponent.GetInstanceIDCompat() } }; } @@ -161,7 +162,7 @@ private static object RemoveComponent(JObject @params, JToken targetToken, strin { success = true, message = $"Component '{componentTypeName}' (index {componentIndex.Value}) removed from '{targetGo.name}'.", - data = new { instanceID = targetGo.GetInstanceID(), componentIndex = componentIndex.Value } + data = new { instanceID = targetGo.GetInstanceIDCompat(), componentIndex = componentIndex.Value } }; } @@ -181,7 +182,7 @@ private static object RemoveComponent(JObject @params, JToken targetToken, strin message = $"Component '{componentTypeName}' removed from '{targetGo.name}'.", data = new { - instanceID = targetGo.GetInstanceID() + instanceID = targetGo.GetInstanceIDCompat() } }; } @@ -277,7 +278,7 @@ private static object SetProperty(JObject @params, JToken targetToken, string se message = $"Some properties failed to set on '{componentType}'.", data = new { - instanceID = targetGo.GetInstanceID(), + instanceID = targetGo.GetInstanceIDCompat(), errors = errors } }; @@ -289,7 +290,7 @@ private static object SetProperty(JObject @params, JToken targetToken, string se message = $"Properties set on component '{componentType}' on '{targetGo.name}'.", data = new { - instanceID = targetGo.GetInstanceID() + instanceID = targetGo.GetInstanceIDCompat() } }; } diff --git a/MCPForUnity/Editor/Tools/ManageMaterial.cs b/MCPForUnity/Editor/Tools/ManageMaterial.cs index ecfb360b0..07270d67a 100644 --- a/MCPForUnity/Editor/Tools/ManageMaterial.cs +++ b/MCPForUnity/Editor/Tools/ManageMaterial.cs @@ -5,6 +5,7 @@ using Newtonsoft.Json.Linq; using UnityEditor; using UnityEngine; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Tools { @@ -417,7 +418,7 @@ private static object CreateUniqueAndAssign(Renderer renderer, GameObject go, Co materialFolder = $"{sceneDir}/Materials"; } - string matPath = $"{materialFolder}/{safeName}_{go.GetInstanceID()}_mat.mat"; + string matPath = $"{materialFolder}/{safeName}_{go.GetInstanceIDCompat()}_mat.mat"; matPath = AssetPathUtility.SanitizeAssetPath(matPath); if (matPath == null) { diff --git a/MCPForUnity/Editor/Tools/ManageScene.cs b/MCPForUnity/Editor/Tools/ManageScene.cs index 4826ea850..7567a78a2 100644 --- a/MCPForUnity/Editor/Tools/ManageScene.cs +++ b/MCPForUnity/Editor/Tools/ManageScene.cs @@ -598,11 +598,7 @@ private static object CaptureScreenshot(SceneCommand cmd) targetCamera = Camera.main; if (targetCamera == null) { -#if UNITY_2022_2_OR_NEWER - var allCams = UnityEngine.Object.FindObjectsByType(FindObjectsSortMode.None); -#else - var allCams = UnityEngine.Object.FindObjectsOfType(); -#endif + var allCams = UnityFindObjectsCompat.FindAll(); targetCamera = allCams.Length > 0 ? allCams[0] : null; } } @@ -640,11 +636,7 @@ private static object CaptureScreenshot(SceneCommand cmd) // Default path: use ScreenCapture API if available, camera fallback otherwise bool screenCaptureAvailable = ScreenshotUtility.IsScreenCaptureModuleAvailable; -#if UNITY_2022_2_OR_NEWER - bool hasCameraFallback = Camera.main != null || UnityEngine.Object.FindObjectsByType(FindObjectsSortMode.None).Length > 0; -#else - bool hasCameraFallback = Camera.main != null || UnityEngine.Object.FindObjectsOfType().Length > 0; -#endif + bool hasCameraFallback = Camera.main != null || UnityFindObjectsCompat.FindAll().Length > 0; #if UNITY_2022_1_OR_NEWER if (!screenCaptureAvailable && !hasCameraFallback) @@ -819,11 +811,7 @@ private static object CaptureSurroundBatch(SceneCommand cmd) // Default: calculate combined bounds of all renderers in the scene Bounds bounds = new Bounds(Vector3.zero, Vector3.zero); bool hasBounds = false; -#if UNITY_2022_2_OR_NEWER - var renderers = UnityEngine.Object.FindObjectsByType(FindObjectsSortMode.None); -#else - var renderers = UnityEngine.Object.FindObjectsOfType(); -#endif + var renderers = UnityFindObjectsCompat.FindAll(); foreach (var r in renderers) { if (r == null || !r.gameObject.activeInHierarchy) continue; @@ -964,11 +952,7 @@ private static object CaptureOrbitBatch(SceneCommand cmd) // Default: calculate combined bounds of all renderers in the scene Bounds bounds = new Bounds(Vector3.zero, Vector3.zero); bool hasBounds = false; -#if UNITY_2022_2_OR_NEWER - var renderers = UnityEngine.Object.FindObjectsByType(FindObjectsSortMode.None); -#else - var renderers = UnityEngine.Object.FindObjectsOfType(); -#endif + var renderers = UnityFindObjectsCompat.FindAll(); foreach (var r in renderers) { if (r == null || !r.gameObject.activeInHierarchy) continue; @@ -1216,11 +1200,7 @@ private static Camera ResolveCamera(string cameraRef) } // Search all cameras by name or path -#if UNITY_2022_2_OR_NEWER - var allCams = UnityEngine.Object.FindObjectsByType(FindObjectsSortMode.None); -#else - var allCams = UnityEngine.Object.FindObjectsOfType(); -#endif + var allCams = UnityFindObjectsCompat.FindAll(); foreach (var cam in allCams) { if (cam.name == cameraRef) return cam; @@ -1272,11 +1252,7 @@ private static object FrameSceneView(SceneCommand cmd) // Frame entire scene by computing combined bounds of all renderers Bounds allBounds = new Bounds(Vector3.zero, Vector3.zero); bool hasAny = false; -#if UNITY_2022_2_OR_NEWER - foreach (var r in UnityEngine.Object.FindObjectsByType(FindObjectsSortMode.None)) -#else - foreach (var r in UnityEngine.Object.FindObjectsOfType()) -#endif + foreach (var r in UnityFindObjectsCompat.FindAll()) { if (r == null || !r.gameObject.activeInHierarchy) continue; if (!hasAny) { allBounds = r.bounds; hasAny = true; } @@ -2008,7 +1984,7 @@ private static object BuildGameObjectSummary(GameObject go, bool includeTransfor var d = new Dictionary { { "name", go.name }, - { "instanceID", go.GetInstanceID() }, + { "instanceID", go.GetInstanceIDCompat() }, { "activeSelf", go.activeSelf }, { "activeInHierarchy", go.activeInHierarchy }, { "tag", go.tag }, diff --git a/MCPForUnity/Editor/Tools/ManageUI.cs b/MCPForUnity/Editor/Tools/ManageUI.cs index 481e47af9..ec1a57c81 100644 --- a/MCPForUnity/Editor/Tools/ManageUI.cs +++ b/MCPForUnity/Editor/Tools/ManageUI.cs @@ -1033,7 +1033,7 @@ private static object RenderUI(JObject @params) return new ErrorResponse("UIDocument has no PanelSettings assigned."); var panelSettings = uiDoc.panelSettings; - int psId = panelSettings.GetInstanceID(); + int psId = panelSettings.GetInstanceIDCompat(); // Check if we already have a persistent RT assigned to this PanelSettings. // If the RT exists and its size matches, the panel has been rendering into it. diff --git a/MCPForUnity/Editor/Tools/Physics/JointOps.cs b/MCPForUnity/Editor/Tools/Physics/JointOps.cs index 0c6906eb0..e367d2dec 100644 --- a/MCPForUnity/Editor/Tools/Physics/JointOps.cs +++ b/MCPForUnity/Editor/Tools/Physics/JointOps.cs @@ -5,6 +5,7 @@ using UnityEditor; using UnityEngine; using MCPForUnity.Editor.Helpers; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Tools.Physics { @@ -140,8 +141,8 @@ public static object AddJoint(JObject @params) data = new { jointType = jointComponentType.Name, - instanceID = joint.GetInstanceID(), - gameObjectInstanceID = go.GetInstanceID() + instanceID = joint.GetInstanceIDCompat(), + gameObjectInstanceID = go.GetInstanceIDCompat() } }; } @@ -312,7 +313,7 @@ public static object ConfigureJoint(JObject @params) { jointType = joint.GetType().Name, configured, - instanceID = joint.GetInstanceID() + instanceID = joint.GetInstanceIDCompat() } }; } @@ -397,7 +398,7 @@ public static object RemoveJoint(JObject @params) data = new { removedCount, - gameObjectInstanceID = go.GetInstanceID() + gameObjectInstanceID = go.GetInstanceIDCompat() } }; } diff --git a/MCPForUnity/Editor/Tools/Physics/PhysicsQueryOps.cs b/MCPForUnity/Editor/Tools/Physics/PhysicsQueryOps.cs index 58580b9b7..9c24d5377 100644 --- a/MCPForUnity/Editor/Tools/Physics/PhysicsQueryOps.cs +++ b/MCPForUnity/Editor/Tools/Physics/PhysicsQueryOps.cs @@ -3,6 +3,7 @@ using Newtonsoft.Json.Linq; using UnityEngine; using MCPForUnity.Editor.Helpers; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Tools.Physics { @@ -79,7 +80,7 @@ private static object Raycast3D(JArray originArr, JArray dirArr, float maxDistan normal = new[] { hitInfo.normal.x, hitInfo.normal.y, hitInfo.normal.z }, distance = hitInfo.distance, gameObject = hitInfo.collider.gameObject.name, - instanceID = hitInfo.collider.gameObject.GetInstanceID(), + instanceID = hitInfo.collider.gameObject.GetInstanceIDCompat(), collider_type = hitInfo.collider.GetType().Name } }; @@ -122,7 +123,7 @@ private static object Raycast2D(JArray originArr, JArray dirArr, float maxDistan normal = new[] { hit.normal.x, hit.normal.y }, distance = hit.distance, gameObject = hit.collider.gameObject.name, - instanceID = hit.collider.gameObject.GetInstanceID(), + instanceID = hit.collider.gameObject.GetInstanceIDCompat(), collider_type = hit.collider.GetType().Name } }; @@ -289,7 +290,7 @@ private static object FormatOverlapResults(Collider[] results, string dimension) colliders.Add(new { gameObject = col.gameObject.name, - instanceID = col.gameObject.GetInstanceID(), + instanceID = col.gameObject.GetInstanceIDCompat(), collider_type = col.GetType().Name }); } @@ -310,7 +311,7 @@ private static object FormatOverlapResults2D(Collider2D[] results, string dimens colliders.Add(new { gameObject = col.gameObject.name, - instanceID = col.gameObject.GetInstanceID(), + instanceID = col.gameObject.GetInstanceIDCompat(), collider_type = col.GetType().Name }); } @@ -464,7 +465,7 @@ private static object Shapecast3D(string shape, JArray originArr, JArray dirArr, normal = new[] { hitInfo.normal.x, hitInfo.normal.y, hitInfo.normal.z }, distance = hitInfo.distance, gameObject = hitInfo.collider.gameObject.name, - instanceID = hitInfo.collider.gameObject.GetInstanceID(), + instanceID = hitInfo.collider.gameObject.GetInstanceIDCompat(), collider_type = hitInfo.collider.GetType().Name } }; @@ -553,7 +554,7 @@ private static object Shapecast2D(string shape, JArray originArr, JArray dirArr, normal = new[] { hit.normal.x, hit.normal.y }, distance = hit.distance, gameObject = hit.collider.gameObject.name, - instanceID = hit.collider.gameObject.GetInstanceID(), + instanceID = hit.collider.gameObject.GetInstanceIDCompat(), collider_type = hit.collider.GetType().Name } }; @@ -619,7 +620,7 @@ private static object RaycastAll3D(JArray originArr, JArray dirArr, float maxDis normal = new[] { h.normal.x, h.normal.y, h.normal.z }, distance = h.distance, gameObject = h.collider.gameObject.name, - instanceID = h.collider.gameObject.GetInstanceID(), + instanceID = h.collider.gameObject.GetInstanceIDCompat(), collider_type = h.collider.GetType().Name }); } @@ -657,7 +658,7 @@ private static object RaycastAll2D(JArray originArr, JArray dirArr, float maxDis normal = new[] { h.normal.x, h.normal.y }, distance = h.distance, gameObject = h.collider.gameObject.name, - instanceID = h.collider.gameObject.GetInstanceID(), + instanceID = h.collider.gameObject.GetInstanceIDCompat(), collider_type = h.collider.GetType().Name }); } @@ -739,7 +740,7 @@ private static object Linecast3D(JArray startArr, JArray endArr, ToolParams p) normal = new[] { hitInfo.normal.x, hitInfo.normal.y, hitInfo.normal.z }, distance = hitInfo.distance, gameObject = hitInfo.collider.gameObject.name, - instanceID = hitInfo.collider.gameObject.GetInstanceID(), + instanceID = hitInfo.collider.gameObject.GetInstanceIDCompat(), collider_type = hitInfo.collider.GetType().Name } }; @@ -782,7 +783,7 @@ private static object Linecast2D(JArray startArr, JArray endArr, ToolParams p) normal = new[] { hit.normal.x, hit.normal.y }, distance = hit.distance, gameObject = hit.collider.gameObject.name, - instanceID = hit.collider.gameObject.GetInstanceID(), + instanceID = hit.collider.gameObject.GetInstanceIDCompat(), collider_type = hit.collider.GetType().Name } }; diff --git a/MCPForUnity/Editor/Tools/Physics/PhysicsRigidbodyOps.cs b/MCPForUnity/Editor/Tools/Physics/PhysicsRigidbodyOps.cs index 098cbd32b..1c2daa034 100644 --- a/MCPForUnity/Editor/Tools/Physics/PhysicsRigidbodyOps.cs +++ b/MCPForUnity/Editor/Tools/Physics/PhysicsRigidbodyOps.cs @@ -4,6 +4,7 @@ using UnityEditor; using UnityEngine; using MCPForUnity.Editor.Helpers; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Tools.Physics { @@ -65,7 +66,7 @@ private static object GetRigidbody3D(GameObject go) var data = new Dictionary { ["target"] = go.name, - ["instanceID"] = go.GetInstanceID(), + ["instanceID"] = go.GetInstanceIDCompat(), ["dimension"] = "3d", ["mass"] = rb.mass, #if UNITY_6000_0_OR_NEWER @@ -113,7 +114,7 @@ private static object GetRigidbody2D(GameObject go) var data = new Dictionary { ["target"] = go.name, - ["instanceID"] = go.GetInstanceID(), + ["instanceID"] = go.GetInstanceIDCompat(), ["dimension"] = "2d", ["mass"] = rb2d.mass, ["gravityScale"] = rb2d.gravityScale, diff --git a/MCPForUnity/Editor/Tools/Physics/PhysicsSimulationOps.cs b/MCPForUnity/Editor/Tools/Physics/PhysicsSimulationOps.cs index 9ef3ae153..8bf4d752a 100644 --- a/MCPForUnity/Editor/Tools/Physics/PhysicsSimulationOps.cs +++ b/MCPForUnity/Editor/Tools/Physics/PhysicsSimulationOps.cs @@ -2,6 +2,7 @@ using MCPForUnity.Editor.Helpers; using Newtonsoft.Json.Linq; using UnityEngine; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Tools.Physics { @@ -97,7 +98,7 @@ private static List CollectTargetRigidbody(string targetStr, string sear results.Add(new { name = go.name, - instanceID = go.GetInstanceID(), + instanceID = go.GetInstanceIDCompat(), position = new[] { rb2d.position.x, rb2d.position.y }, #if UNITY_6000_0_OR_NEWER velocity = new[] { rb2d.linearVelocity.x, rb2d.linearVelocity.y }, @@ -116,7 +117,7 @@ private static List CollectTargetRigidbody(string targetStr, string sear results.Add(new { name = go.name, - instanceID = go.GetInstanceID(), + instanceID = go.GetInstanceIDCompat(), position = new[] { rb.position.x, rb.position.y, rb.position.z }, #if UNITY_6000_0_OR_NEWER velocity = new[] { rb.linearVelocity.x, rb.linearVelocity.y, rb.linearVelocity.z }, @@ -138,11 +139,7 @@ private static List CollectActiveRigidbodies(string dimension) if (dimension == "2d") { -#if UNITY_2022_2_OR_NEWER - var allRb2d = Object.FindObjectsByType(FindObjectsSortMode.None); -#else - var allRb2d = Object.FindObjectsOfType(); -#endif + var allRb2d = UnityFindObjectsCompat.FindAll(); foreach (var rb2d in allRb2d) { if (results.Count >= maxResults) break; @@ -152,7 +149,7 @@ private static List CollectActiveRigidbodies(string dimension) results.Add(new { name = rb2d.gameObject.name, - instanceID = rb2d.gameObject.GetInstanceID(), + instanceID = rb2d.gameObject.GetInstanceIDCompat(), position = new[] { rb2d.position.x, rb2d.position.y }, #if UNITY_6000_0_OR_NEWER velocity = new[] { rb2d.linearVelocity.x, rb2d.linearVelocity.y }, @@ -165,11 +162,7 @@ private static List CollectActiveRigidbodies(string dimension) } else { -#if UNITY_2022_2_OR_NEWER - var allRb = Object.FindObjectsByType(FindObjectsSortMode.None); -#else - var allRb = Object.FindObjectsOfType(); -#endif + var allRb = UnityFindObjectsCompat.FindAll(); foreach (var rb in allRb) { if (results.Count >= maxResults) break; @@ -179,7 +172,7 @@ private static List CollectActiveRigidbodies(string dimension) results.Add(new { name = rb.gameObject.name, - instanceID = rb.gameObject.GetInstanceID(), + instanceID = rb.gameObject.GetInstanceIDCompat(), position = new[] { rb.position.x, rb.position.y, rb.position.z }, #if UNITY_6000_0_OR_NEWER velocity = new[] { rb.linearVelocity.x, rb.linearVelocity.y, rb.linearVelocity.z }, diff --git a/MCPForUnity/Editor/Tools/Prefabs/ManagePrefabs.cs b/MCPForUnity/Editor/Tools/Prefabs/ManagePrefabs.cs index 812f86d57..6b6e79bd8 100644 --- a/MCPForUnity/Editor/Tools/Prefabs/ManagePrefabs.cs +++ b/MCPForUnity/Editor/Tools/Prefabs/ManagePrefabs.cs @@ -8,6 +8,7 @@ using UnityEditor.SceneManagement; using UnityEngine; using UnityEngine.SceneManagement; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Tools.Prefabs { @@ -162,7 +163,7 @@ private static object CreatePrefabFromGameObject(JObject @params) new { prefabPath = finalPath, - instanceId = result.GetInstanceID(), + instanceId = result.GetInstanceIDCompat(), instanceName = result.name, wasUnlinked = unlinkIfInstance && objectValidation.shouldUnlink, wasReplaced = replaceExisting && fileExistedAtPath, @@ -1234,7 +1235,7 @@ private static void BuildHierarchyItemsRecursive(Transform transform, Transform string name = transform.gameObject.name; string path = string.IsNullOrEmpty(parentPath) ? name : $"{parentPath}/{name}"; - int instanceId = transform.gameObject.GetInstanceID(); + int instanceId = transform.gameObject.GetInstanceIDCompat(); bool activeSelf = transform.gameObject.activeSelf; int childCount = transform.childCount; var componentTypes = PrefabUtilityHelper.GetComponentTypeNames(transform.gameObject); diff --git a/MCPForUnity/Editor/Tools/ProBuilder/ManageProBuilder.cs b/MCPForUnity/Editor/Tools/ProBuilder/ManageProBuilder.cs index 618ded368..cedbb0d34 100644 --- a/MCPForUnity/Editor/Tools/ProBuilder/ManageProBuilder.cs +++ b/MCPForUnity/Editor/Tools/ProBuilder/ManageProBuilder.cs @@ -6,6 +6,7 @@ using MCPForUnity.Editor.Helpers; using UnityEditor; using UnityEngine; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Tools.ProBuilder { @@ -595,7 +596,7 @@ private static object CreateShape(JObject @params) return new SuccessResponse($"Created ProBuilder {shapeTypeStr}: {go.name}", new { gameObjectName = go.name, - instanceId = go.GetInstanceID(), + instanceId = go.GetInstanceIDCompat(), shapeType = shapeTypeStr, faceCount = GetFaceCount(pbMesh), vertexCount = GetVertexCount(pbMesh), @@ -899,7 +900,7 @@ private static object CreatePolyShape(JObject @params) return new SuccessResponse($"Created poly shape: {go.name}", new { gameObjectName = go.name, - instanceId = go.GetInstanceID(), + instanceId = go.GetInstanceIDCompat(), pointCount = points.Count, extrudeHeight, faceCount = GetFaceCount(pbMesh), @@ -2294,7 +2295,7 @@ private static object GetMeshInfo(JObject @params) var data = new Dictionary { ["gameObjectName"] = pbMesh.gameObject.name, - ["instanceId"] = pbMesh.gameObject.GetInstanceID(), + ["instanceId"] = pbMesh.gameObject.GetInstanceIDCompat(), ["faceCount"] = GetFaceCount(pbMesh), ["vertexCount"] = GetVertexCount(pbMesh), ["bounds"] = new diff --git a/MCPForUnity/Editor/Tools/Vfx/ParticleControl.cs b/MCPForUnity/Editor/Tools/Vfx/ParticleControl.cs index 98f2270ed..18e542b6e 100644 --- a/MCPForUnity/Editor/Tools/Vfx/ParticleControl.cs +++ b/MCPForUnity/Editor/Tools/Vfx/ParticleControl.cs @@ -3,6 +3,7 @@ using UnityEditor; using UnityEngine; using MCPForUnity.Editor.Helpers; +using MCPForUnity.Runtime.Helpers; namespace MCPForUnity.Editor.Tools.Vfx { @@ -90,7 +91,7 @@ public static object Create(JObject @params) success = true, message = $"ParticleSystem ready on '{go.name}'", target = go.name, - targetId = go.GetInstanceID(), + targetId = go.GetInstanceIDCompat(), createdGameObject, addedParticleSystem, assignedMaterial = renderer?.sharedMaterial?.name diff --git a/MCPForUnity/Runtime/Helpers/ScreenshotUtility.cs b/MCPForUnity/Runtime/Helpers/ScreenshotUtility.cs index 6c32cd62b..188e612ba 100644 --- a/MCPForUnity/Runtime/Helpers/ScreenshotUtility.cs +++ b/MCPForUnity/Runtime/Helpers/ScreenshotUtility.cs @@ -91,11 +91,7 @@ private static Camera FindAvailableCamera() try { -#if UNITY_2022_2_OR_NEWER - var cams = UnityEngine.Object.FindObjectsByType(FindObjectsSortMode.None); -#else - var cams = UnityEngine.Object.FindObjectsOfType(); -#endif + var cams = UnityFindObjectsCompat.FindAll(); return cams.FirstOrDefault(); } catch diff --git a/MCPForUnity/Runtime/Helpers/UnityFindObjectsCompat.cs b/MCPForUnity/Runtime/Helpers/UnityFindObjectsCompat.cs new file mode 100644 index 000000000..076d9097a --- /dev/null +++ b/MCPForUnity/Runtime/Helpers/UnityFindObjectsCompat.cs @@ -0,0 +1,64 @@ +using System; +using UObject = UnityEngine.Object; + +namespace MCPForUnity.Runtime.Helpers +{ + /// + /// Version-compatible wrappers for the Object.FindObjectsOfType / FindObjectsByType family, + /// which changed across Unity 2022 → 6.0 → 6.5: + /// Pre-2022.2 : FindObjectsOfType / FindObjectOfType + /// 2022.2–6.4 : FindObjectsByType(sortMode) / FindFirstObjectByType + /// 6.5+ : FindObjectsByType() (no sort param) / FindAnyObjectByType + /// + public static class UnityFindObjectsCompat + { + /// Find all active objects of type T. + public static T[] FindAll() where T : UObject + { +#if UNITY_6000_5_OR_NEWER + return UObject.FindObjectsByType(); +#elif UNITY_2022_2_OR_NEWER + return UObject.FindObjectsByType(UnityEngine.FindObjectsSortMode.None); +#else + return UObject.FindObjectsOfType(); +#endif + } + + /// Find all active objects of the given runtime type. + public static UObject[] FindAll(Type type) + { +#if UNITY_6000_5_OR_NEWER + return UObject.FindObjectsByType(type, UnityEngine.FindObjectsInactive.Exclude); +#elif UNITY_2022_2_OR_NEWER + return UObject.FindObjectsByType(type, UnityEngine.FindObjectsSortMode.None); +#else + return UObject.FindObjectsOfType(type); +#endif + } + + /// Find all objects of the given runtime type, optionally including inactive. + public static UObject[] FindAll(Type type, bool includeInactive) + { +#if UNITY_6000_5_OR_NEWER + return UObject.FindObjectsByType(type, + includeInactive ? UnityEngine.FindObjectsInactive.Include : UnityEngine.FindObjectsInactive.Exclude); +#elif UNITY_2023_1_OR_NEWER + return UObject.FindObjectsByType(type, + includeInactive ? UnityEngine.FindObjectsInactive.Include : UnityEngine.FindObjectsInactive.Exclude, + UnityEngine.FindObjectsSortMode.None); +#else + return UObject.FindObjectsOfType(type, includeInactive); +#endif + } + + /// Find any single object of the given runtime type (no ordering guarantee). + public static UObject FindAny(Type type) + { +#if UNITY_2022_2_OR_NEWER + return UObject.FindAnyObjectByType(type); +#else + return UObject.FindObjectOfType(type); +#endif + } + } +} diff --git a/MCPForUnity/Runtime/Helpers/UnityFindObjectsCompat.cs.meta b/MCPForUnity/Runtime/Helpers/UnityFindObjectsCompat.cs.meta new file mode 100644 index 000000000..195437795 --- /dev/null +++ b/MCPForUnity/Runtime/Helpers/UnityFindObjectsCompat.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 7c3a9f12e4b60438d9a1c52ef8d07b3e \ No newline at end of file diff --git a/MCPForUnity/Runtime/Helpers/UnityObjectIdCompatExtensions.cs b/MCPForUnity/Runtime/Helpers/UnityObjectIdCompatExtensions.cs new file mode 100644 index 000000000..ca3278dc0 --- /dev/null +++ b/MCPForUnity/Runtime/Helpers/UnityObjectIdCompatExtensions.cs @@ -0,0 +1,30 @@ +using UnityEngine; + +namespace MCPForUnity.Runtime.Helpers +{ + /// + /// Version-gated wrapper for , which was removed in Unity 6.5 + /// in favor of . Returns a session-scoped int handle that + /// callers can use for in-process comparisons and wire-format compatibility with older readers. + /// For deserialization round-trips on Unity 6.5+, prefer the full entityID field. + /// + public static class UnityObjectIdCompatExtensions + { + public static int GetInstanceIDCompat(this Object obj) + { + if (obj == null) + { + return 0; + } + +#if UNITY_6000_5_OR_NEWER + // GetInstanceID() is obsolete-as-error on Unity 6.5+. Truncate the EntityId's + // underlying ulong to int; this is lossy but stable within a session and + // preserves the int-shaped wire format that older consumers expect. + return (int)EntityId.ToULong(obj.GetEntityId()); +#else + return obj.GetInstanceID(); +#endif + } + } +} diff --git a/MCPForUnity/Runtime/Helpers/UnityObjectIdCompatExtensions.cs.meta b/MCPForUnity/Runtime/Helpers/UnityObjectIdCompatExtensions.cs.meta new file mode 100644 index 000000000..b6879c4a4 --- /dev/null +++ b/MCPForUnity/Runtime/Helpers/UnityObjectIdCompatExtensions.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 5ea8b580f3e80459cab9019f71d0ccb6 \ No newline at end of file diff --git a/MCPForUnity/Runtime/Serialization/UnityTypeConverters.cs b/MCPForUnity/Runtime/Serialization/UnityTypeConverters.cs index b593fb98e..0491d61df 100644 --- a/MCPForUnity/Runtime/Serialization/UnityTypeConverters.cs +++ b/MCPForUnity/Runtime/Serialization/UnityTypeConverters.cs @@ -2,6 +2,7 @@ using Newtonsoft.Json.Linq; using System; using UnityEngine; +using MCPForUnity.Runtime.Helpers; #if UNITY_EDITOR using UnityEditor; // Required for AssetDatabase and EditorUtility #endif @@ -294,8 +295,7 @@ public override void WriteJson(JsonWriter writer, UnityEngine.Object value, Json writer.WriteStartObject(); writer.WritePropertyName("name"); writer.WriteValue(value.name); - writer.WritePropertyName("instanceID"); - writer.WriteValue(value.GetInstanceID()); + WriteSerializedObjectId(writer, value); writer.WritePropertyName("isAssetWithoutPath"); writer.WriteValue(true); writer.WriteEndObject(); @@ -307,8 +307,7 @@ public override void WriteJson(JsonWriter writer, UnityEngine.Object value, Json writer.WriteStartObject(); writer.WritePropertyName("name"); writer.WriteValue(value.name); - writer.WritePropertyName("instanceID"); - writer.WriteValue(value.GetInstanceID()); + WriteSerializedObjectId(writer, value); writer.WriteEndObject(); } #else @@ -316,8 +315,7 @@ public override void WriteJson(JsonWriter writer, UnityEngine.Object value, Json writer.WriteStartObject(); writer.WritePropertyName("name"); writer.WriteValue(value.name); - writer.WritePropertyName("instanceID"); - writer.WriteValue(value.GetInstanceID()); + WriteSerializedObjectId(writer, value); writer.WritePropertyName("warning"); writer.WriteValue("UnityEngineObjectConverter running in non-Editor mode, asset path unavailable."); writer.WriteEndObject(); @@ -376,6 +374,42 @@ public override UnityEngine.Object ReadJson(JsonReader reader, Type objectType, return null; } +#if UNITY_6000_5_OR_NEWER + // Try to resolve by entityID (Unity 6.5+). Falls through to instanceID/guid/path on failure. + if (jo.TryGetValue("entityID", out JToken entityIdToken) && entityIdToken.Type == JTokenType.String) + { + string serializedEntityId = entityIdToken.ToString(); + if (ulong.TryParse(serializedEntityId, out ulong rawEntityId)) + { + EntityId eid = EntityId.FromULong(rawEntityId); + UnityEngine.Object entityObj = UnityEditor.EditorUtility.EntityIdToObject(eid); + if (entityObj != null) + { + if (objectType.IsAssignableFrom(entityObj.GetType())) + { + return entityObj; + } + + if (objectType == typeof(Transform) && entityObj is GameObject entityGo) + { + return entityGo.transform; + } + + if (typeof(Component).IsAssignableFrom(objectType) && entityObj is GameObject entityGameObj) + { + var component = entityGameObj.GetComponent(objectType); + if (component != null) + { + return component; + } + } + } + } + + UnityEngine.Debug.LogWarning($"[UnityEngineObjectConverter] Could not resolve entityID '{serializedEntityId}' to a valid {objectType.Name}. Falling back to instanceID/guid/path."); + } +#endif + // Try to resolve by instanceID if (jo.TryGetValue("instanceID", out JToken idToken) && idToken.Type == JTokenType.Integer) { @@ -435,7 +469,7 @@ public override UnityEngine.Object ReadJson(JsonReader reader, Type objectType, } // Object format not recognized - UnityEngine.Debug.LogWarning($"[UnityEngineObjectConverter] JSON object missing 'instanceID', 'guid', or 'path' field for {objectType.Name} deserialization. Object: {jo.ToString(Formatting.None)}"); + UnityEngine.Debug.LogWarning($"[UnityEngineObjectConverter] JSON object missing 'instanceID', 'entityID', 'guid', or 'path' field for {objectType.Name} deserialization. Object: {jo.ToString(Formatting.None)}"); return null; } @@ -467,5 +501,18 @@ private static bool IsValidGuid(string str) } return true; } + + private static void WriteSerializedObjectId(JsonWriter writer, UnityEngine.Object value) + { + // Always emit instanceID so older consumers keep working. + writer.WritePropertyName("instanceID"); + writer.WriteValue(value.GetInstanceIDCompat()); +#if UNITY_6000_5_OR_NEWER + // Additionally emit entityID on Unity 6.5+ as the stable ulong form + // (per Unity docs, EntityId.ToString() is NOT a stable serialization format). + writer.WritePropertyName("entityID"); + writer.WriteValue(EntityId.ToULong(value.GetEntityId()).ToString()); +#endif + } } } \ No newline at end of file