-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathManagePrefabs.cs
More file actions
1426 lines (1260 loc) · 59.7 KB
/
ManagePrefabs.cs
File metadata and controls
1426 lines (1260 loc) · 59.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using MCPForUnity.Editor.Helpers;
using Newtonsoft.Json.Linq;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
using MCPForUnity.Runtime.Helpers;
namespace MCPForUnity.Editor.Tools.Prefabs
{
[McpForUnityTool("manage_prefabs", AutoRegister = false)]
/// <summary>
/// Tool to manage Unity Prefabs: create, inspect, modify, and open/save/close prefab stage.
/// Supports both headless editing (modify_contents) and interactive prefab stage workflows.
/// </summary>
public static class ManagePrefabs
{
// Action constants
private const string ACTION_CREATE_FROM_GAMEOBJECT = "create_from_gameobject";
private const string ACTION_GET_INFO = "get_info";
private const string ACTION_GET_HIERARCHY = "get_hierarchy";
private const string ACTION_MODIFY_CONTENTS = "modify_contents";
private const string ACTION_OPEN_PREFAB_STAGE = "open_prefab_stage";
private const string ACTION_SAVE_PREFAB_STAGE = "save_prefab_stage";
private const string ACTION_CLOSE_PREFAB_STAGE = "close_prefab_stage";
private const string SupportedActions = ACTION_CREATE_FROM_GAMEOBJECT + ", " + ACTION_GET_INFO + ", " + ACTION_GET_HIERARCHY + ", " + ACTION_MODIFY_CONTENTS + ", " + ACTION_OPEN_PREFAB_STAGE + ", " + ACTION_SAVE_PREFAB_STAGE + ", " + ACTION_CLOSE_PREFAB_STAGE;
public static object HandleCommand(JObject @params)
{
if (@params == null)
{
return new ErrorResponse("Parameters cannot be null.");
}
string action = @params["action"]?.ToString()?.ToLowerInvariant();
if (string.IsNullOrEmpty(action))
{
return new ErrorResponse($"Action parameter is required. Valid actions are: {SupportedActions}.");
}
try
{
switch (action)
{
case ACTION_CREATE_FROM_GAMEOBJECT:
return CreatePrefabFromGameObject(@params);
case ACTION_GET_INFO:
return GetInfo(@params);
case ACTION_GET_HIERARCHY:
return GetHierarchy(@params);
case ACTION_MODIFY_CONTENTS:
return ModifyContents(@params);
case ACTION_OPEN_PREFAB_STAGE:
{
string prefabPath = @params["prefabPath"]?.ToString() ?? @params["path"]?.ToString();
return OpenPrefabStage(prefabPath);
}
case ACTION_SAVE_PREFAB_STAGE:
{
bool refresh = @params["refresh"]?.ToObject<bool>() ?? true;
return SavePrefabStage(refresh);
}
case ACTION_CLOSE_PREFAB_STAGE:
{
bool saveBeforeClose = @params["saveBeforeClose"]?.ToObject<bool>() ?? false;
bool refresh = @params["refresh"]?.ToObject<bool>() ?? true;
return ClosePrefabStage(saveBeforeClose, refresh);
}
default:
return new ErrorResponse($"Unknown action: '{action}'. Valid actions are: {SupportedActions}.");
}
}
catch (Exception e)
{
McpLog.Error($"[ManagePrefabs] Action '{action}' failed: {e}");
return new ErrorResponse($"Internal error: {e.Message}");
}
}
#region Create Prefab from GameObject
/// <summary>
/// Creates a prefab asset from a GameObject in the scene.
/// </summary>
private static object CreatePrefabFromGameObject(JObject @params)
{
// 1. Validate and parse parameters
var validation = ValidateCreatePrefabParams(@params);
if (!validation.isValid)
{
return new ErrorResponse(validation.errorMessage);
}
string targetName = validation.targetName;
string finalPath = validation.finalPath;
bool includeInactive = validation.includeInactive;
bool replaceExisting = validation.replaceExisting;
bool unlinkIfInstance = validation.unlinkIfInstance;
// 2. Find the source object
GameObject sourceObject = FindSceneObjectByName(targetName, includeInactive);
if (sourceObject == null)
{
return new ErrorResponse($"GameObject '{targetName}' not found in the active scene or prefab stage{(includeInactive ? " (including inactive objects)" : "")}.");
}
// 3. Validate source object state
var objectValidation = ValidateSourceObjectForPrefab(sourceObject, unlinkIfInstance);
if (!objectValidation.isValid)
{
return new ErrorResponse(objectValidation.errorMessage);
}
// 4. Check for path conflicts and track if file will be replaced
bool fileExistedAtPath = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(finalPath) != null;
if (!replaceExisting && fileExistedAtPath)
{
finalPath = AssetDatabase.GenerateUniqueAssetPath(finalPath);
McpLog.Info($"[ManagePrefabs] Generated unique path: {finalPath}");
}
// 5. Ensure directory exists
EnsureAssetDirectoryExists(finalPath);
// 6. Unlink from existing prefab if needed
if (unlinkIfInstance && objectValidation.shouldUnlink)
{
try
{
// UnpackPrefabInstance requires the prefab instance root, not a child object
GameObject rootToUnlink = PrefabUtility.GetOutermostPrefabInstanceRoot(sourceObject);
if (rootToUnlink != null)
{
PrefabUtility.UnpackPrefabInstance(rootToUnlink, PrefabUnpackMode.Completely, InteractionMode.AutomatedAction);
McpLog.Info($"[ManagePrefabs] Unpacked prefab instance '{rootToUnlink.name}' before creating new prefab.");
}
}
catch (Exception e)
{
return new ErrorResponse($"Failed to unlink prefab instance: {e.Message}");
}
}
// 7. Persist any runtime-only materials so they survive prefab serialization
var persistResult = PersistRuntimeMaterials(sourceObject, finalPath);
// 8. Create the prefab
try
{
GameObject result = CreatePrefabAsset(sourceObject, finalPath, replaceExisting);
if (result == null)
{
return new ErrorResponse($"Failed to create prefab asset at '{finalPath}'.");
}
// 9. Select the newly created instance
Selection.activeGameObject = result;
return new SuccessResponse(
$"Prefab created at '{finalPath}' and instance linked.",
new
{
prefabPath = finalPath,
instanceId = result.GetInstanceIDCompat(),
instanceName = result.name,
wasUnlinked = unlinkIfInstance && objectValidation.shouldUnlink,
wasReplaced = replaceExisting && fileExistedAtPath,
componentCount = result.GetComponents<Component>().Length,
childCount = result.transform.childCount,
materialsPersisted = persistResult.count
}
);
}
catch (Exception e)
{
McpLog.Error($"[ManagePrefabs] Error creating prefab at '{finalPath}': {e}");
return new ErrorResponse($"Error saving prefab asset: {e.Message}");
}
}
/// <summary>
/// Validates parameters for creating a prefab from GameObject.
/// </summary>
private static (bool isValid, string errorMessage, string targetName, string finalPath, bool includeInactive, bool replaceExisting, bool unlinkIfInstance)
ValidateCreatePrefabParams(JObject @params)
{
string targetName = @params["target"]?.ToString() ?? @params["name"]?.ToString();
if (string.IsNullOrEmpty(targetName))
{
return (false, "'target' parameter is required for create_from_gameobject.", null, null, false, false, false);
}
string requestedPath = @params["prefabPath"]?.ToString();
if (string.IsNullOrWhiteSpace(requestedPath))
{
return (false, "'prefabPath' parameter is required for create_from_gameobject.", targetName, null, false, false, false);
}
string sanitizedPath = AssetPathUtility.SanitizeAssetPath(requestedPath);
if (sanitizedPath == null)
{
return (false, $"Invalid prefab path (path traversal detected): '{requestedPath}'", targetName, null, false, false, false);
}
if (string.IsNullOrEmpty(sanitizedPath))
{
return (false, $"Invalid prefab path '{requestedPath}'. Path cannot be empty.", targetName, null, false, false, false);
}
if (!sanitizedPath.EndsWith(".prefab", StringComparison.OrdinalIgnoreCase))
{
sanitizedPath += ".prefab";
}
// Validate path is within Assets folder
if (!sanitizedPath.StartsWith("Assets/", StringComparison.OrdinalIgnoreCase))
{
return (false, $"Prefab path must be within the Assets folder. Got: '{sanitizedPath}'", targetName, null, false, false, false);
}
bool includeInactive = @params["searchInactive"]?.ToObject<bool>() ?? false;
bool replaceExisting = @params["allowOverwrite"]?.ToObject<bool>() ?? false;
bool unlinkIfInstance = @params["unlinkIfInstance"]?.ToObject<bool>() ?? false;
return (true, null, targetName, sanitizedPath, includeInactive, replaceExisting, unlinkIfInstance);
}
/// <summary>
/// Validates source object can be converted to prefab.
/// </summary>
private static (bool isValid, string errorMessage, bool shouldUnlink, string existingPrefabPath)
ValidateSourceObjectForPrefab(GameObject sourceObject, bool unlinkIfInstance)
{
// Check if this is a Prefab Asset (the .prefab file itself in the editor)
if (PrefabUtility.IsPartOfPrefabAsset(sourceObject))
{
return (false,
$"GameObject '{sourceObject.name}' is part of a prefab asset. " +
"Open the prefab stage to save changes instead.",
false, null);
}
// Check if this is already a Prefab Instance
PrefabInstanceStatus status = PrefabUtility.GetPrefabInstanceStatus(sourceObject);
if (status != PrefabInstanceStatus.NotAPrefab)
{
string existingPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(sourceObject);
if (!unlinkIfInstance)
{
return (false,
$"GameObject '{sourceObject.name}' is already linked to prefab '{existingPath}'. " +
"Set 'unlinkIfInstance' to true to unlink it first, or modify the existing prefab instead.",
false, existingPath);
}
// Needs to be unlinked
return (true, null, true, existingPath);
}
return (true, null, false, null);
}
/// <summary>
/// Creates a prefab asset from a GameObject.
/// </summary>
private static GameObject CreatePrefabAsset(GameObject sourceObject, string path, bool replaceExisting)
{
GameObject result = PrefabUtility.SaveAsPrefabAssetAndConnect(
sourceObject,
path,
InteractionMode.AutomatedAction
);
string action = replaceExisting ? "Replaced existing" : "Created new";
McpLog.Info($"[ManagePrefabs] {action} prefab at '{path}'.");
if (result != null)
{
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
return result;
}
/// <summary>
/// Scans all Renderers in the hierarchy and persists any runtime-only materials
/// (MaterialPropertyBlock overrides or in-memory instances from renderer.material)
/// as .mat assets so they survive prefab serialization.
/// </summary>
private static (int count, List<string> paths) PersistRuntimeMaterials(GameObject root, string prefabPath)
{
var renderers = root.GetComponentsInChildren<Renderer>(true);
var persistedPaths = new List<string>();
string prefabDir = Path.GetDirectoryName(prefabPath).Replace("\\", "/");
string materialsFolder = $"{prefabDir}/Materials";
foreach (var renderer in renderers)
{
Material[] sharedMats = renderer.sharedMaterials;
bool changed = false;
for (int slot = 0; slot < sharedMats.Length; slot++)
{
Material mat = sharedMats[slot];
// Case 1: Material is null but a property block has color data —
// this happens after instance mode severs the asset link.
// Case 2: Material exists but is not a persistent asset (runtime instance).
bool isRuntimeInstance = mat != null && !EditorUtility.IsPersistent(mat);
bool isNullWithPropertyBlock = mat == null && HasPropertyBlockColors(renderer, slot);
bool isNullMaterial = mat == null && !isNullWithPropertyBlock;
if (!isRuntimeInstance && !isNullWithPropertyBlock)
continue;
// Derive a unique asset path from the GameObject name and slot
string goName = renderer.gameObject.name.Replace(" ", "_");
string suffix = slot > 0 ? $"_slot{slot}" : "";
string matPath = $"{materialsFolder}/{goName}{suffix}_mat.mat";
matPath = AssetPathUtility.SanitizeAssetPath(matPath);
if (matPath == null)
{
McpLog.Warn($"[ManagePrefabs] Could not build safe material path for '{renderer.gameObject.name}', skipping.");
continue;
}
// Ensure the Materials directory exists (recursive)
EnsureAssetFolderExists(materialsFolder);
Material persisted = AssetDatabase.LoadAssetAtPath<Material>(matPath);
if (persisted == null)
{
// Create a new material with the correct shader for the active pipeline
Shader shader = isRuntimeInstance && mat.shader != null
? mat.shader
: RenderPipelineUtility.ResolveShader("Standard");
persisted = new Material(shader);
AssetDatabase.CreateAsset(persisted, matPath);
}
// Copy properties from the runtime instance if available
if (isRuntimeInstance)
{
persisted.CopyPropertiesFromMaterial(mat);
EditorUtility.SetDirty(persisted);
}
else if (isNullWithPropertyBlock)
{
// Extract color from the property block and apply to the new material
ApplyPropertyBlockToMaterial(renderer, slot, persisted);
EditorUtility.SetDirty(persisted);
}
sharedMats[slot] = persisted;
changed = true;
persistedPaths.Add(matPath);
McpLog.Info($"[ManagePrefabs] Persisted runtime material for '{renderer.gameObject.name}' slot {slot} → {matPath}");
}
if (changed)
{
Undo.RecordObject(renderer, "Persist runtime materials for prefab");
renderer.sharedMaterials = sharedMats;
// Clear any property blocks now that the material is persisted
for (int slot = 0; slot < sharedMats.Length; slot++)
{
renderer.SetPropertyBlock(null, slot);
}
EditorUtility.SetDirty(renderer);
}
}
if (persistedPaths.Count > 0)
{
AssetDatabase.SaveAssets();
McpLog.Info($"[ManagePrefabs] Persisted {persistedPaths.Count} runtime material(s) before prefab save.");
}
return (persistedPaths.Count, persistedPaths);
}
/// <summary>
/// Recursively creates the folder hierarchy for the given asset path if it doesn't exist.
/// </summary>
private static void EnsureAssetFolderExists(string assetFolderPath)
{
if (AssetDatabase.IsValidFolder(assetFolderPath))
return;
string[] parts = assetFolderPath.Replace('\\', '/').Split('/');
string current = parts[0]; // "Assets"
for (int i = 1; i < parts.Length; i++)
{
string next = current + "/" + parts[i];
if (!AssetDatabase.IsValidFolder(next))
AssetDatabase.CreateFolder(current, parts[i]);
current = next;
}
}
private static bool HasPropertyBlockColors(Renderer renderer, int slot)
{
MaterialPropertyBlock block = new MaterialPropertyBlock();
renderer.GetPropertyBlock(block, slot);
return !block.isEmpty;
}
/// <summary>
/// Extracts color properties from a MaterialPropertyBlock and applies them to a material.
/// </summary>
private static void ApplyPropertyBlockToMaterial(Renderer renderer, int slot, Material mat)
{
MaterialPropertyBlock block = new MaterialPropertyBlock();
renderer.GetPropertyBlock(block, slot);
// Try the standard color property names
string[] colorProps = { "_BaseColor", "_Color" };
foreach (string prop in colorProps)
{
if (mat.HasProperty(prop) && block.HasColor(prop))
{
mat.SetColor(prop, block.GetColor(prop));
}
}
}
#endregion
/// <summary>
/// Ensures the directory for an asset path exists, creating it if necessary.
/// </summary>
private static void EnsureAssetDirectoryExists(string assetPath)
{
string directory = Path.GetDirectoryName(assetPath);
if (string.IsNullOrEmpty(directory))
{
return;
}
// Use Application.dataPath for more reliable path resolution
// Application.dataPath points to the Assets folder (e.g., ".../ProjectName/Assets")
string assetsPath = Application.dataPath;
string projectRoot = Path.GetDirectoryName(assetsPath);
string fullDirectory = Path.Combine(projectRoot, directory);
if (!Directory.Exists(fullDirectory))
{
Directory.CreateDirectory(fullDirectory);
AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
McpLog.Info($"[ManagePrefabs] Created directory: {directory}");
}
}
/// <summary>
/// Finds a GameObject by name in the active scene or current prefab stage.
/// </summary>
private static GameObject FindSceneObjectByName(string name, bool includeInactive)
{
// First check if we're in Prefab Stage
PrefabStage stage = PrefabStageUtility.GetCurrentPrefabStage();
if (stage?.prefabContentsRoot != null)
{
foreach (Transform transform in stage.prefabContentsRoot.GetComponentsInChildren<Transform>(includeInactive))
{
if (transform.name == name && (includeInactive || transform.gameObject.activeSelf))
{
return transform.gameObject;
}
}
}
// Search in the active scene
Scene activeScene = SceneManager.GetActiveScene();
foreach (GameObject root in activeScene.GetRootGameObjects())
{
// Check the root object itself
if (root.name == name && (includeInactive || root.activeSelf))
{
return root;
}
// Check children
foreach (Transform transform in root.GetComponentsInChildren<Transform>(includeInactive))
{
if (transform.name == name && (includeInactive || transform.gameObject.activeSelf))
{
return transform.gameObject;
}
}
}
return null;
}
#region Read Operations
/// <summary>
/// Gets basic metadata information about a prefab asset.
/// </summary>
private static object GetInfo(JObject @params)
{
string prefabPath = @params["prefabPath"]?.ToString() ?? @params["path"]?.ToString();
if (string.IsNullOrEmpty(prefabPath))
{
return new ErrorResponse("'prefabPath' parameter is required for get_info.");
}
string sanitizedPath = AssetPathUtility.SanitizeAssetPath(prefabPath);
if (string.IsNullOrEmpty(sanitizedPath))
{
return new ErrorResponse($"Invalid prefab path: '{prefabPath}'.");
}
GameObject prefabAsset = AssetDatabase.LoadAssetAtPath<GameObject>(sanitizedPath);
if (prefabAsset == null)
{
return new ErrorResponse($"No prefab asset found at path '{sanitizedPath}'.");
}
string guid = PrefabUtilityHelper.GetPrefabGUID(sanitizedPath);
PrefabAssetType assetType = PrefabUtility.GetPrefabAssetType(prefabAsset);
string prefabTypeString = assetType.ToString();
var componentTypes = PrefabUtilityHelper.GetComponentTypeNames(prefabAsset);
int childCount = PrefabUtilityHelper.CountChildrenRecursive(prefabAsset.transform);
var (isVariant, parentPrefab, _) = PrefabUtilityHelper.GetVariantInfo(prefabAsset);
return new SuccessResponse(
$"Successfully retrieved prefab info.",
new
{
assetPath = sanitizedPath,
guid = guid,
prefabType = prefabTypeString,
rootObjectName = prefabAsset.name,
rootComponentTypes = componentTypes,
childCount = childCount,
isVariant = isVariant,
parentPrefab = parentPrefab
}
);
}
/// <summary>
/// Gets the hierarchical structure of a prefab asset.
/// Returns all objects in the prefab for full client-side filtering and search.
/// </summary>
private static object GetHierarchy(JObject @params)
{
string prefabPath = @params["prefabPath"]?.ToString() ?? @params["path"]?.ToString();
if (string.IsNullOrEmpty(prefabPath))
{
return new ErrorResponse("'prefabPath' parameter is required for get_hierarchy.");
}
string sanitizedPath = AssetPathUtility.SanitizeAssetPath(prefabPath);
if (string.IsNullOrEmpty(sanitizedPath))
{
return new ErrorResponse($"Invalid prefab path '{prefabPath}'. Path traversal sequences are not allowed.");
}
// Load prefab contents in background (without opening stage UI)
GameObject prefabContents = PrefabUtility.LoadPrefabContents(sanitizedPath);
if (prefabContents == null)
{
return new ErrorResponse($"Failed to load prefab contents from '{sanitizedPath}'.");
}
try
{
// Build complete hierarchy items (no pagination)
var allItems = BuildHierarchyItems(prefabContents.transform, sanitizedPath);
return new SuccessResponse(
$"Successfully retrieved prefab hierarchy. Found {allItems.Count} objects.",
new
{
prefabPath = sanitizedPath,
total = allItems.Count,
items = allItems
}
);
}
finally
{
// Always unload prefab contents to free memory
PrefabUtility.UnloadPrefabContents(prefabContents);
}
}
#endregion
#region Headless Prefab Editing
/// <summary>
/// Modifies a prefab's contents directly without opening the prefab stage.
/// This is ideal for automated/agentic workflows as it avoids UI, dirty flags, and dialogs.
/// </summary>
private static object ModifyContents(JObject @params)
{
string prefabPath = @params["prefabPath"]?.ToString() ?? @params["path"]?.ToString();
if (string.IsNullOrEmpty(prefabPath))
{
return new ErrorResponse("'prefabPath' parameter is required for modify_contents.");
}
string sanitizedPath = AssetPathUtility.SanitizeAssetPath(prefabPath);
if (string.IsNullOrEmpty(sanitizedPath))
{
return new ErrorResponse($"Invalid prefab path '{prefabPath}'. Path traversal sequences are not allowed.");
}
// Load prefab contents in isolated context (no UI)
GameObject prefabContents = PrefabUtility.LoadPrefabContents(sanitizedPath);
if (prefabContents == null)
{
return new ErrorResponse($"Failed to load prefab contents from '{sanitizedPath}'.");
}
try
{
// Find target object within the prefab (defaults to root)
string targetName = @params["target"]?.ToString();
GameObject targetGo = FindInPrefabContents(prefabContents, targetName);
if (targetGo == null)
{
string searchedFor = string.IsNullOrEmpty(targetName) ? "root" : $"'{targetName}'";
return new ErrorResponse($"Target {searchedFor} not found in prefab '{sanitizedPath}'.");
}
// Apply modifications
var modifyResult = ApplyModificationsToPrefabObject(targetGo, @params, prefabContents, sanitizedPath);
if (modifyResult.error != null)
{
return modifyResult.error;
}
// Skip saving when no modifications were made to avoid unnecessary asset writes
if (!modifyResult.modified)
{
return new SuccessResponse(
$"Prefab '{sanitizedPath}' is already up to date; no changes were applied.",
new
{
prefabPath = sanitizedPath,
targetName = targetGo.name,
modified = false
}
);
}
// Save the prefab
bool success;
PrefabUtility.SaveAsPrefabAsset(prefabContents, sanitizedPath, out success);
if (!success)
{
return new ErrorResponse($"Failed to save prefab asset at '{sanitizedPath}'.");
}
AssetDatabase.Refresh();
McpLog.Info($"[ManagePrefabs] Successfully modified and saved prefab '{sanitizedPath}' (headless).");
return new SuccessResponse(
$"Prefab '{sanitizedPath}' modified and saved successfully.",
new
{
prefabPath = sanitizedPath,
targetName = targetGo.name,
modified = modifyResult.modified,
transform = new
{
position = new { x = targetGo.transform.localPosition.x, y = targetGo.transform.localPosition.y, z = targetGo.transform.localPosition.z },
rotation = new { x = targetGo.transform.localEulerAngles.x, y = targetGo.transform.localEulerAngles.y, z = targetGo.transform.localEulerAngles.z },
scale = new { x = targetGo.transform.localScale.x, y = targetGo.transform.localScale.y, z = targetGo.transform.localScale.z }
},
componentTypes = PrefabUtilityHelper.GetComponentTypeNames(targetGo)
}
);
}
finally
{
// Always unload prefab contents to free memory
PrefabUtility.UnloadPrefabContents(prefabContents);
}
}
/// <summary>
/// Finds a GameObject within loaded prefab contents by name or path.
/// </summary>
private static GameObject FindInPrefabContents(GameObject prefabContents, string target)
{
if (string.IsNullOrEmpty(target))
{
// Return root if no target specified
return prefabContents;
}
// Try to find by path first (e.g., "Parent/Child/Target")
if (target.Contains("/"))
{
Transform found = prefabContents.transform.Find(target);
if (found != null)
{
return found.gameObject;
}
// If path starts with root name, try without it
if (target.StartsWith(prefabContents.name + "/"))
{
string relativePath = target.Substring(prefabContents.name.Length + 1);
found = prefabContents.transform.Find(relativePath);
if (found != null)
{
return found.gameObject;
}
}
}
// Check if target matches root name
if (prefabContents.name == target)
{
return prefabContents;
}
// Search by name in hierarchy
foreach (Transform t in prefabContents.GetComponentsInChildren<Transform>(true))
{
if (t.gameObject.name == target)
{
return t.gameObject;
}
}
return null;
}
/// <summary>
/// Applies modifications to a GameObject within loaded prefab contents.
/// Returns (modified: bool, error: ErrorResponse or null).
/// </summary>
private static (bool modified, ErrorResponse error) ApplyModificationsToPrefabObject(GameObject targetGo, JObject @params, GameObject prefabRoot, string editingPrefabPath)
{
bool modified = false;
// Name change
string newName = @params["name"]?.ToString();
if (!string.IsNullOrEmpty(newName) && targetGo.name != newName)
{
// If renaming the root, this will affect the prefab asset name on save
targetGo.name = newName;
modified = true;
}
// Active state
bool? setActive = @params["setActive"]?.ToObject<bool?>();
if (setActive.HasValue && targetGo.activeSelf != setActive.Value)
{
targetGo.SetActive(setActive.Value);
modified = true;
}
// Tag
string tag = @params["tag"]?.ToString();
if (tag != null && targetGo.tag != tag)
{
string tagToSet = string.IsNullOrEmpty(tag) ? "Untagged" : tag;
try
{
targetGo.tag = tagToSet;
modified = true;
}
catch (Exception ex)
{
return (false, new ErrorResponse($"Failed to set tag to '{tagToSet}': {ex.Message}"));
}
}
// Layer
string layerName = @params["layer"]?.ToString();
if (!string.IsNullOrEmpty(layerName))
{
int layerId = LayerMask.NameToLayer(layerName);
if (layerId == -1)
{
return (false, new ErrorResponse($"Invalid layer specified: '{layerName}'. Use a valid layer name."));
}
if (targetGo.layer != layerId)
{
targetGo.layer = layerId;
modified = true;
}
}
// Transform: position, rotation, scale
Vector3? position = VectorParsing.ParseVector3(@params["position"]);
Vector3? rotation = VectorParsing.ParseVector3(@params["rotation"]);
Vector3? scale = VectorParsing.ParseVector3(@params["scale"]);
if (position.HasValue && targetGo.transform.localPosition != position.Value)
{
targetGo.transform.localPosition = position.Value;
modified = true;
}
if (rotation.HasValue && targetGo.transform.localEulerAngles != rotation.Value)
{
targetGo.transform.localEulerAngles = rotation.Value;
modified = true;
}
if (scale.HasValue && targetGo.transform.localScale != scale.Value)
{
targetGo.transform.localScale = scale.Value;
modified = true;
}
// Parent change (within prefab hierarchy)
JToken parentToken = @params["parent"];
if (parentToken != null)
{
string parentTarget = parentToken.ToString();
Transform newParent = null;
if (!string.IsNullOrEmpty(parentTarget))
{
GameObject parentGo = FindInPrefabContents(prefabRoot, parentTarget);
if (parentGo == null)
{
return (false, new ErrorResponse($"Parent '{parentTarget}' not found in prefab."));
}
if (parentGo.transform.IsChildOf(targetGo.transform))
{
return (false, new ErrorResponse($"Cannot parent '{targetGo.name}' to '{parentGo.name}' as it would create a hierarchy loop."));
}
newParent = parentGo.transform;
}
if (targetGo.transform.parent != newParent)
{
targetGo.transform.SetParent(newParent, true);
modified = true;
}
}
// Components to add
if (@params["componentsToAdd"] is JArray componentsToAdd)
{
foreach (var compToken in componentsToAdd)
{
string typeName = compToken.Type == JTokenType.String
? compToken.ToString()
: (compToken as JObject)?["typeName"]?.ToString();
if (!string.IsNullOrEmpty(typeName))
{
if (!ComponentResolver.TryResolve(typeName, out Type componentType, out string error))
{
return (false, new ErrorResponse($"Component type '{typeName}' not found: {error}"));
}
targetGo.AddComponent(componentType);
modified = true;
}
}
}
// Components to remove
if (@params["componentsToRemove"] is JArray componentsToRemove)
{
foreach (var compToken in componentsToRemove)
{
string typeName = compToken.ToString();
if (!string.IsNullOrEmpty(typeName))
{
if (!ComponentResolver.TryResolve(typeName, out Type componentType, out string error))
{
return (false, new ErrorResponse($"Component type '{typeName}' not found: {error}"));
}
Component comp = targetGo.GetComponent(componentType);
if (comp != null)
{
UnityEngine.Object.DestroyImmediate(comp);
modified = true;
}
}
}
}
// Create child GameObjects (supports single object or array)
JToken createChildToken = @params["createChild"] ?? @params["create_child"];
if (createChildToken != null)
{
// Handle array of children
if (createChildToken is JArray childArray)
{
foreach (var childToken in childArray)
{
var childResult = CreateSingleChildInPrefab(childToken, targetGo, prefabRoot, editingPrefabPath);
if (childResult.error != null)
{
return (false, childResult.error);
}
if (childResult.created)
{
modified = true;
}
}
}
else
{
// Handle single child object
var childResult = CreateSingleChildInPrefab(createChildToken, targetGo, prefabRoot, editingPrefabPath);
if (childResult.error != null)
{
return (false, childResult.error);
}
if (childResult.created)
{
modified = true;
}
}
}
// Delete child GameObjects (supports single string or array of paths/names)
JToken deleteChildToken = @params["deleteChild"] ?? @params["delete_child"];
if (deleteChildToken != null)
{
var deleteResult = RemoveChildren(deleteChildToken, targetGo, prefabRoot);
if (deleteResult.error != null)
{
return (false, deleteResult.error);
}
if (deleteResult.removedCount > 0)
{
modified = true;
}
}
// Set properties on existing components
JObject componentProperties = @params["componentProperties"] as JObject ?? @params["component_properties"] as JObject;
if (componentProperties != null && componentProperties.Count > 0)
{
var errors = new List<string>();
foreach (var entry in componentProperties.Properties())
{
string typeName = entry.Name;
if (!ComponentResolver.TryResolve(typeName, out Type componentType, out string resolveError))
{
errors.Add($"{typeName}: type not found — {resolveError}");
continue;
}
Component component = targetGo.GetComponent(componentType);
if (component == null)
{
errors.Add($"{typeName}: not found on '{targetGo.name}'");
continue;
}
if (entry.Value is not JObject props || !props.HasValues)
{
continue;
}
foreach (var prop in props.Properties())
{
if (!ComponentOps.SetProperty(component, prop.Name, prop.Value, out string setError))
{
errors.Add($"{typeName}.{prop.Name}: {setError}");
}
else
{
modified = true;
}
}
}
if (errors.Count > 0)
{
return (false, new ErrorResponse($"Failed to set component properties (no changes saved): {string.Join("; ", errors)}"));
}
}
return (modified, null);
}
/// <summary>
/// Creates a single child GameObject within the prefab contents.
/// </summary>
private static (bool created, ErrorResponse error) CreateSingleChildInPrefab(JToken createChildToken, GameObject defaultParent, GameObject prefabRoot, string editingPrefabPath)
{
JObject childParams;
if (createChildToken is JObject obj)
{
childParams = obj;