forked from CoplayDev/unity-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathManageScriptableObject.cs
More file actions
1501 lines (1325 loc) · 64.9 KB
/
ManageScriptableObject.cs
File metadata and controls
1501 lines (1325 loc) · 64.9 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 System.Text.RegularExpressions;
using MCPForUnity.Editor.Helpers;
using Newtonsoft.Json.Linq;
using UnityEditor;
using UnityEngine;
namespace MCPForUnity.Editor.Tools
{
/// <summary>
/// Single tool for ScriptableObject workflows:
/// - action=create: create a ScriptableObject asset (and optionally apply patches)
/// - action=modify: apply serialized property patches to an existing asset
///
/// Patching is performed via SerializedObject/SerializedProperty paths (Unity-native), not reflection.
/// </summary>
[McpForUnityTool("manage_scriptable_object", AutoRegister = false, Group = "scripting_ext")]
public static class ManageScriptableObject
{
private const string CodeCompilingOrReloading = "compiling_or_reloading";
private const string CodeInvalidParams = "invalid_params";
private const string CodeTypeNotFound = "type_not_found";
private const string CodeInvalidFolderPath = "invalid_folder_path";
private const string CodeTargetNotFound = "target_not_found";
private const string CodeAssetCreateFailed = "asset_create_failed";
private static readonly HashSet<string> ValidActions = new(StringComparer.OrdinalIgnoreCase)
{
// NOTE: Action strings are normalized by NormalizeAction() (lowercased, '_'/'-' removed),
// so we only need the canonical normalized forms here.
"create",
"createso",
"modify",
"modifyso",
};
public static object HandleCommand(JObject @params)
{
if (@params == null)
{
return new ErrorResponse(CodeInvalidParams);
}
if (EditorApplication.isCompiling || EditorApplication.isUpdating)
{
// Unity is transient; treat as retryable on the client side.
return new ErrorResponse(CodeCompilingOrReloading, new { hint = "retry" });
}
// Allow JSON-string parameters for objects/arrays.
JsonUtil.CoerceJsonStringParameter(@params, "target");
CoerceJsonStringArrayParameter(@params, "patches");
string actionRaw = @params["action"]?.ToString();
if (string.IsNullOrWhiteSpace(actionRaw))
{
return new ErrorResponse(CodeInvalidParams, new { message = "'action' is required.", validActions = ValidActions.ToArray() });
}
string action = NormalizeAction(actionRaw);
if (!ValidActions.Contains(action))
{
return new ErrorResponse(CodeInvalidParams, new { message = $"Unknown action: '{actionRaw}'.", validActions = ValidActions.ToArray() });
}
if (IsCreateAction(action))
{
return HandleCreate(@params);
}
return HandleModify(@params);
}
private static object HandleCreate(JObject @params)
{
string typeName = @params["typeName"]?.ToString() ?? @params["type_name"]?.ToString();
string folderPath = @params["folderPath"]?.ToString() ?? @params["folder_path"]?.ToString();
string assetName = @params["assetName"]?.ToString() ?? @params["asset_name"]?.ToString();
bool overwrite = @params["overwrite"]?.ToObject<bool?>() ?? false;
if (string.IsNullOrWhiteSpace(typeName))
{
return new ErrorResponse(CodeInvalidParams, new { message = "'typeName' is required." });
}
if (string.IsNullOrWhiteSpace(folderPath))
{
return new ErrorResponse(CodeInvalidParams, new { message = "'folderPath' is required." });
}
if (string.IsNullOrWhiteSpace(assetName))
{
return new ErrorResponse(CodeInvalidParams, new { message = "'assetName' is required." });
}
if (assetName.Contains("/") || assetName.Contains("\\"))
{
return new ErrorResponse(CodeInvalidParams, new { message = "'assetName' must not contain path separators." });
}
if (!TryNormalizeFolderPath(folderPath, out var normalizedFolder, out var folderNormalizeError))
{
return new ErrorResponse(CodeInvalidFolderPath, new { message = folderNormalizeError, folderPath });
}
if (!EnsureFolderExists(normalizedFolder, out var folderError))
{
return new ErrorResponse(CodeInvalidFolderPath, new { message = folderError, folderPath = normalizedFolder });
}
var resolvedType = ResolveType(typeName);
if (resolvedType == null || !typeof(ScriptableObject).IsAssignableFrom(resolvedType))
{
return new ErrorResponse(CodeTypeNotFound, new { message = $"ScriptableObject type not found: '{typeName}'", typeName });
}
string fileName = assetName.EndsWith(".asset", StringComparison.OrdinalIgnoreCase)
? assetName
: assetName + ".asset";
string desiredPath = $"{normalizedFolder.TrimEnd('/')}/{fileName}";
string finalPath = overwrite ? desiredPath : AssetDatabase.GenerateUniqueAssetPath(desiredPath);
ScriptableObject instance;
try
{
instance = ScriptableObject.CreateInstance(resolvedType);
if (instance == null)
{
return new ErrorResponse(CodeAssetCreateFailed, new { message = "CreateInstance returned null.", typeName = resolvedType.FullName });
}
}
catch (Exception ex)
{
return new ErrorResponse(CodeAssetCreateFailed, new { message = ex.Message, typeName = resolvedType.FullName });
}
// GUID-preserving overwrite logic
bool isNewAsset = true;
try
{
if (overwrite)
{
var existingAsset = AssetDatabase.LoadAssetAtPath<ScriptableObject>(finalPath);
if (existingAsset != null && existingAsset.GetType() == resolvedType)
{
// Preserve GUID by overwriting existing asset data in-place
EditorUtility.CopySerialized(instance, existingAsset);
// Fix for "Main Object Name does not match filename" warning:
// CopySerialized overwrites the name with the (empty) name of the new instance.
// We must restore the correct name to match the filename.
existingAsset.name = Path.GetFileNameWithoutExtension(finalPath);
UnityEngine.Object.DestroyImmediate(instance); // Destroy temporary instance
instance = existingAsset; // Proceed with patching the existing asset
isNewAsset = false;
// Mark dirty to ensure changes are picked up
EditorUtility.SetDirty(instance);
}
else if (existingAsset != null)
{
// Type mismatch or not a ScriptableObject - must delete and recreate to change type, losing GUID
// (Or we could warn, but overwrite usually implies replacing)
AssetDatabase.DeleteAsset(finalPath);
}
}
if (isNewAsset)
{
// Ensure the new instance has the correct name before creating asset to avoid warnings
instance.name = Path.GetFileNameWithoutExtension(finalPath);
AssetDatabase.CreateAsset(instance, finalPath);
}
}
catch (Exception ex)
{
return new ErrorResponse(CodeAssetCreateFailed, new { message = ex.Message, path = finalPath });
}
string guid = AssetDatabase.AssetPathToGUID(finalPath);
var patchesToken = @params["patches"];
object patchResults = null;
var warnings = new List<string>();
if (patchesToken is JArray patches && patches.Count > 0)
{
var patchApply = ApplyPatches(instance, patches);
patchResults = patchApply.results;
warnings.AddRange(patchApply.warnings);
}
EditorUtility.SetDirty(instance);
AssetDatabase.SaveAssets();
return new SuccessResponse(
"ScriptableObject created.",
new
{
guid,
path = finalPath,
typeNameResolved = resolvedType.FullName,
patchResults,
warnings = warnings.Count > 0 ? warnings : null
}
);
}
private static object HandleModify(JObject @params)
{
if (!TryResolveTarget(@params["target"], out var target, out var targetPath, out var targetGuid, out var err))
{
return err;
}
var patchesToken = @params["patches"];
if (patchesToken == null || patchesToken.Type == JTokenType.Null)
{
return new ErrorResponse(CodeInvalidParams, new { message = "'patches' is required.", targetPath, targetGuid });
}
if (patchesToken is not JArray patches)
{
return new ErrorResponse(CodeInvalidParams, new { message = "'patches' must be an array.", targetPath, targetGuid });
}
// Phase 5: Dry-run mode - validate patches without applying
bool dryRun = @params["dryRun"]?.ToObject<bool?>() ?? @params["dry_run"]?.ToObject<bool?>() ?? false;
if (dryRun)
{
var validationResults = ValidatePatches(target, patches);
return new SuccessResponse(
"Dry-run validation complete.",
new
{
targetGuid,
targetPath,
targetTypeName = target.GetType().FullName,
dryRun = true,
valid = validationResults.All(r => (bool)r.GetType().GetProperty("ok")?.GetValue(r)),
validationResults
}
);
}
var (results, warnings) = ApplyPatches(target, patches);
return new SuccessResponse(
"Serialized properties patched.",
new
{
targetGuid,
targetPath,
targetTypeName = target.GetType().FullName,
results,
warnings = warnings.Count > 0 ? warnings : null
}
);
}
/// <summary>
/// Validates patches without applying them (for dry-run mode).
/// Checks that property paths exist and that value types are compatible.
/// </summary>
private static List<object> ValidatePatches(UnityEngine.Object target, JArray patches)
{
var results = new List<object>(patches.Count);
var so = new SerializedObject(target);
so.Update();
for (int i = 0; i < patches.Count; i++)
{
if (patches[i] is not JObject patchObj)
{
results.Add(new { index = i, propertyPath = "", op = "", ok = false, message = $"Patch at index {i} must be an object." });
continue;
}
string propertyPath = patchObj["propertyPath"]?.ToString()
?? patchObj["property_path"]?.ToString()
?? patchObj["path"]?.ToString();
string op = (patchObj["op"]?.ToString() ?? "set").Trim();
if (string.IsNullOrWhiteSpace(propertyPath))
{
results.Add(new { index = i, propertyPath = propertyPath ?? "", op, ok = false, message = "Missing required field: propertyPath" });
continue;
}
// Normalize the path
string normalizedPath = NormalizePropertyPath(propertyPath);
string normalizedOp = op.ToLowerInvariant();
// For array_resize, check if the array exists
if (normalizedOp == "array_resize")
{
var valueToken = patchObj["value"];
if (valueToken == null || valueToken.Type == JTokenType.Null)
{
results.Add(new { index = i, propertyPath = normalizedPath, op, ok = false, message = "array_resize requires integer 'value'." });
continue;
}
int size = ParamCoercion.CoerceInt(valueToken, -1);
if (size < 0)
{
results.Add(new { index = i, propertyPath = normalizedPath, op, ok = false, message = "array_resize requires non-negative integer 'value'." });
continue;
}
// Check if the array path exists
string arrayPath = normalizedPath;
if (arrayPath.EndsWith(".Array.size", StringComparison.Ordinal))
{
arrayPath = arrayPath.Substring(0, arrayPath.Length - ".Array.size".Length);
}
var arrayProp = so.FindProperty(arrayPath);
if (arrayProp == null)
{
results.Add(new { index = i, propertyPath = normalizedPath, op, ok = false, message = $"Array not found: {arrayPath}" });
continue;
}
if (!arrayProp.isArray)
{
results.Add(new { index = i, propertyPath = normalizedPath, op, ok = false, message = $"Property is not an array: {arrayPath}" });
continue;
}
results.Add(new { index = i, propertyPath = normalizedPath, op, ok = true, message = $"Will resize to {size}.", currentSize = arrayProp.arraySize });
continue;
}
// For set operations, check if the property exists (or can be auto-grown)
var prop = so.FindProperty(normalizedPath);
// Check if it's an auto-growable array element path
bool isAutoGrowable = false;
if (prop == null)
{
var match = Regex.Match(normalizedPath, @"^(.+?)\.Array\.data\[(\d+)\]");
if (match.Success)
{
string arrayPath = match.Groups[1].Value;
var arrayProp = so.FindProperty(arrayPath);
if (arrayProp != null && arrayProp.isArray)
{
isAutoGrowable = true;
// Get the element type info from existing elements or report as growable
int targetIndex = int.Parse(match.Groups[2].Value);
if (arrayProp.arraySize > 0)
{
var sampleElement = arrayProp.GetArrayElementAtIndex(0);
results.Add(new {
index = i,
propertyPath = normalizedPath,
op,
ok = true,
message = $"Will auto-grow array from {arrayProp.arraySize} to {targetIndex + 1}.",
elementType = sampleElement?.propertyType.ToString() ?? "unknown"
});
}
else
{
results.Add(new {
index = i,
propertyPath = normalizedPath,
op,
ok = true,
message = $"Will auto-grow empty array to size {targetIndex + 1}."
});
}
continue;
}
}
}
if (prop == null && !isAutoGrowable)
{
results.Add(new { index = i, propertyPath = normalizedPath, op, ok = false, message = $"Property not found: {normalizedPath}" });
continue;
}
if (prop != null)
{
// Property exists - validate value format for supported complex types
var valueToken = patchObj["value"];
string valueValidationMsg = null;
bool valueFormatOk = true;
// Enhanced dry-run: validate value format for AnimationCurve and Quaternion
// Uses shared validators from VectorParsing
if (valueToken != null && valueToken.Type != JTokenType.Null)
{
switch (prop.propertyType)
{
case SerializedPropertyType.AnimationCurve:
valueFormatOk = VectorParsing.ValidateAnimationCurveFormat(valueToken, out valueValidationMsg);
break;
case SerializedPropertyType.Quaternion:
valueFormatOk = VectorParsing.ValidateQuaternionFormat(valueToken, out valueValidationMsg);
break;
}
}
if (valueFormatOk)
{
results.Add(new {
index = i,
propertyPath = normalizedPath,
op,
ok = true,
message = valueValidationMsg ?? "Property found.",
propertyType = prop.propertyType.ToString(),
isArray = prop.isArray
});
}
else
{
results.Add(new {
index = i,
propertyPath = normalizedPath,
op,
ok = false,
message = valueValidationMsg,
propertyType = prop.propertyType.ToString(),
isArray = prop.isArray
});
}
}
}
return results;
}
private static (List<object> results, List<string> warnings) ApplyPatches(UnityEngine.Object target, JArray patches)
{
var warnings = new List<string>();
var results = new List<object>(patches.Count);
bool anyChanged = false;
var so = new SerializedObject(target);
so.Update();
for (int i = 0; i < patches.Count; i++)
{
if (patches[i] is not JObject patchObj)
{
results.Add(new { propertyPath = "", op = "", ok = false, message = $"Patch at index {i} must be an object." });
continue;
}
string propertyPath = patchObj["propertyPath"]?.ToString()
?? patchObj["property_path"]?.ToString()
?? patchObj["path"]?.ToString();
string op = (patchObj["op"]?.ToString() ?? "set").Trim();
if (string.IsNullOrWhiteSpace(propertyPath))
{
results.Add(new { propertyPath = propertyPath ?? "", op, ok = false, message = "Missing required field: propertyPath" });
continue;
}
if (string.IsNullOrWhiteSpace(op))
{
op = "set";
}
var patchResult = ApplyPatch(so, propertyPath, op, patchObj, out bool changed);
anyChanged |= changed;
results.Add(patchResult);
// Array resize should be applied immediately so later paths resolve.
if (string.Equals(op, "array_resize", StringComparison.OrdinalIgnoreCase) && changed)
{
so.ApplyModifiedProperties();
so.Update();
}
}
if (anyChanged)
{
so.ApplyModifiedProperties();
EditorUtility.SetDirty(target);
AssetDatabase.SaveAssets();
}
return (results, warnings);
}
private static object ApplyPatch(SerializedObject so, string propertyPath, string op, JObject patchObj, out bool changed)
{
changed = false;
try
{
// Phase 1.1: Normalize friendly path syntax (e.g., myList[5] → myList.Array.data[5])
string normalizedPath = NormalizePropertyPath(propertyPath);
string normalizedOp = op.Trim().ToLowerInvariant();
switch (normalizedOp)
{
case "array_resize":
return ApplyArrayResize(so, normalizedPath, patchObj, out changed);
case "set":
default:
return ApplySet(so, normalizedPath, patchObj, out changed);
}
}
catch (Exception ex)
{
return new { propertyPath, op, ok = false, message = ex.Message };
}
}
/// <summary>
/// Normalizes friendly property path syntax to Unity's internal format.
/// Converts bracket notation (e.g., myList[5]) to Unity's Array.data format (myList.Array.data[5]).
/// </summary>
private static string NormalizePropertyPath(string path)
{
if (string.IsNullOrEmpty(path))
return path;
// Pattern: word[number] where it's not already in .Array.data[number] format
// We need to handle cases like: myList[5], nested.list[0].field, etc.
// But NOT: myList.Array.data[5] (already in Unity format)
// Replace fieldName[index] with fieldName.Array.data[index]
// But only if it's not already in Array.data format
return Regex.Replace(path, @"(\w+)\[(\d+)\]", m =>
{
string fieldName = m.Groups[1].Value;
string index = m.Groups[2].Value;
// Check if this match is already part of .Array.data[index] pattern
// by checking if the text immediately before the field name is ".Array."
// and the field name is "data"
int matchStart = m.Index;
if (fieldName == "data" && matchStart >= 7) // Length of ".Array."
{
string preceding = path.Substring(matchStart - 7, 7);
if (preceding == ".Array.")
{
// Already in Unity format (e.g., myList.Array.data[0]), return as-is
return m.Value;
}
}
return $"{fieldName}.Array.data[{index}]";
});
}
/// <summary>
/// Ensures an array has sufficient capacity for the given index.
/// Automatically resizes the array if the target index is beyond current bounds.
/// </summary>
/// <param name="so">The SerializedObject containing the array</param>
/// <param name="path">The normalized property path (must be in Array.data format)</param>
/// <param name="resized">True if the array was resized</param>
/// <returns>True if the path is valid for setting, false if it cannot be resolved</returns>
private static bool EnsureArrayCapacity(SerializedObject so, string path, out bool resized)
{
resized = false;
// Match pattern: something.Array.data[N]
var match = Regex.Match(path, @"^(.+?)\.Array\.data\[(\d+)\]");
if (!match.Success)
{
// Not an array element path, nothing to do
return true;
}
string arrayPath = match.Groups[1].Value;
if (!int.TryParse(match.Groups[2].Value, out int targetIndex))
{
return false;
}
var arrayProp = so.FindProperty(arrayPath);
if (arrayProp == null || !arrayProp.isArray)
{
// Array property not found or not an array
return false;
}
if (arrayProp.arraySize <= targetIndex)
{
// Need to grow the array
arrayProp.arraySize = targetIndex + 1;
so.ApplyModifiedProperties();
so.Update();
resized = true;
}
return true;
}
private static object ApplyArrayResize(SerializedObject so, string propertyPath, JObject patchObj, out bool changed)
{
changed = false;
// Use ParamCoercion for robust int parsing
var valueToken = patchObj["value"];
if (valueToken == null || valueToken.Type == JTokenType.Null)
{
return new { propertyPath, op = "array_resize", ok = false, message = "array_resize requires integer 'value'." };
}
int newSize = ParamCoercion.CoerceInt(valueToken, -1);
if (newSize < 0)
{
return new { propertyPath, op = "array_resize", ok = false, message = "array_resize requires integer 'value'." };
}
newSize = Math.Max(0, newSize);
// Unity supports resizing either:
// - the array/list property itself (prop.isArray -> prop.arraySize)
// - the synthetic leaf property "<array>.Array.size" (prop.intValue)
//
// Different Unity versions/serialization edge cases can fail to resolve the synthetic leaf via FindProperty
// (or can return different property types), so we keep a "best-effort" fallback:
// - Prefer acting on the requested path if it resolves.
// - If the requested path doesn't resolve, try to resolve the *array property* and set arraySize directly.
SerializedProperty prop = so.FindProperty(propertyPath);
SerializedProperty arrayProp = null;
if (propertyPath.EndsWith(".Array.size", StringComparison.Ordinal))
{
// Caller explicitly targeted the synthetic leaf. Resolve the parent array property as a fallback
// (Unity sometimes fails to resolve the synthetic leaf in certain serialization contexts).
var arrayPath = propertyPath.Substring(0, propertyPath.Length - ".Array.size".Length);
arrayProp = so.FindProperty(arrayPath);
}
else
{
// Caller targeted either the array property itself (e.g., "items") or some other property.
// If it's already an array, we can resize it directly. Otherwise, we attempt to resolve
// a synthetic ".Array.size" leaf as a convenience, which some clients may pass.
arrayProp = prop != null && prop.isArray ? prop : so.FindProperty(propertyPath + ".Array.size");
}
if (prop == null)
{
// If we failed to find the direct property but we *can* find the array property, use that.
if (arrayProp != null && arrayProp.isArray)
{
if (arrayProp.arraySize != newSize)
{
arrayProp.arraySize = newSize;
changed = true;
}
return new
{
propertyPath,
op = "array_resize",
ok = true,
resolvedPropertyType = "Array",
message = $"Set array size to {newSize}."
};
}
return new { propertyPath, op = "array_resize", ok = false, message = $"Property not found: {propertyPath}" };
}
// Unity may represent ".Array.size" as either Integer or ArraySize depending on version.
if ((prop.propertyType == SerializedPropertyType.Integer || prop.propertyType == SerializedPropertyType.ArraySize)
&& propertyPath.EndsWith(".Array.size", StringComparison.Ordinal))
{
// We successfully resolved the synthetic leaf; write the size through its intValue.
if (prop.intValue != newSize)
{
prop.intValue = newSize;
changed = true;
}
return new { propertyPath, op = "array_resize", ok = true, resolvedPropertyType = prop.propertyType.ToString(), message = $"Set array size to {newSize}." };
}
if (prop.isArray)
{
// We resolved the array property itself; write through arraySize.
if (prop.arraySize != newSize)
{
prop.arraySize = newSize;
changed = true;
}
return new { propertyPath, op = "array_resize", ok = true, resolvedPropertyType = "Array", message = $"Set array size to {newSize}." };
}
return new { propertyPath, op = "array_resize", ok = false, resolvedPropertyType = prop.propertyType.ToString(), message = $"Property is not an array or array-size field: {propertyPath}" };
}
private static object ApplySet(SerializedObject so, string propertyPath, JObject patchObj, out bool changed)
{
changed = false;
// Phase 1.2: Auto-resize arrays if targeting an index beyond current bounds
if (!EnsureArrayCapacity(so, propertyPath, out bool arrayResized))
{
// Could not resolve the array path - try to find the property anyway for a better error message
var checkProp = so.FindProperty(propertyPath);
if (checkProp == null)
{
// Try to provide helpful context about what went wrong
var arrayMatch = Regex.Match(propertyPath, @"^(.+?)\.Array\.data\[(\d+)\]");
if (arrayMatch.Success)
{
string arrayPath = arrayMatch.Groups[1].Value;
var arrayProp = so.FindProperty(arrayPath);
if (arrayProp == null)
{
return new { propertyPath, op = "set", ok = false, message = $"Array property not found: {arrayPath}" };
}
if (!arrayProp.isArray)
{
return new { propertyPath, op = "set", ok = false, message = $"Property is not an array: {arrayPath}" };
}
}
return new { propertyPath, op = "set", ok = false, message = $"Property not found: {propertyPath}" };
}
}
var prop = so.FindProperty(propertyPath);
if (prop == null)
{
return new { propertyPath, op = "set", ok = false, message = $"Property not found: {propertyPath}" };
}
// Track if we resized - this counts as a change
if (arrayResized)
{
changed = true;
}
if (prop.propertyType == SerializedPropertyType.ObjectReference)
{
// Legacy "ref" key takes precedence for backward compatibility.
// Use TryGetValue to preserve non-JObject ref tokens (e.g. string GUID).
patchObj.TryGetValue("ref", out JToken refToken);
var objRefValue = patchObj["value"];
JToken resolveToken = refToken ?? objRefValue;
if (resolveToken == null)
{
return new { propertyPath, op = "set", ok = false, resolvedPropertyType = prop.propertyType.ToString(),
message = "ObjectReference patch requires a 'ref' or 'value' key." };
}
if (!ComponentOps.SetObjectReference(prop, resolveToken, out string refError))
{
return new { propertyPath, op = "set", ok = false, resolvedPropertyType = prop.propertyType.ToString(), message = refError };
}
changed = true;
string refMessage = prop.objectReferenceValue == null
? "Cleared reference."
: $"Set reference to '{prop.objectReferenceValue.name}'.";
return new { propertyPath, op = "set", ok = true, resolvedPropertyType = prop.propertyType.ToString(), message = refMessage };
}
var valueToken = patchObj["value"];
if (valueToken == null)
{
return new { propertyPath, op = "set", ok = false, resolvedPropertyType = prop.propertyType.ToString(), message = "Missing required field: value" };
}
bool ok = TrySetValue(prop, valueToken, out string message);
changed = ok;
return new { propertyPath, op = "set", ok, resolvedPropertyType = prop.propertyType.ToString(), message };
}
private static bool TrySetValue(SerializedProperty prop, JToken valueToken, out string message)
{
return TrySetValueRecursive(prop, valueToken, out message, 0);
}
/// <summary>
/// Recursively sets values on SerializedProperties, supporting bulk array and object mapping.
/// </summary>
/// <param name="prop">The property to set</param>
/// <param name="valueToken">The JSON value</param>
/// <param name="message">Output message describing the result</param>
/// <param name="depth">Current recursion depth (for safety limits)</param>
private static bool TrySetValueRecursive(SerializedProperty prop, JToken valueToken, out string message, int depth)
{
message = null;
const int MaxRecursionDepth = 20;
if (depth > MaxRecursionDepth)
{
message = $"Maximum recursion depth ({MaxRecursionDepth}) exceeded. Check for circular references.";
return false;
}
try
{
// Phase 3.1: Handle bulk array mapping - JArray value for array/list properties
if (prop.isArray && prop.propertyType != SerializedPropertyType.String && valueToken is JArray jArray)
{
// Resize the array to match the JSON array
prop.arraySize = jArray.Count;
// Get the SerializedObject and apply so we can access elements
var so = prop.serializedObject;
so.ApplyModifiedProperties();
so.Update();
int successCount = 0;
var errors = new List<string>();
for (int i = 0; i < jArray.Count; i++)
{
var elementProp = prop.GetArrayElementAtIndex(i);
if (elementProp == null)
{
errors.Add($"Could not get element at index {i}");
continue;
}
if (TrySetValueRecursive(elementProp, jArray[i], out string elemMessage, depth + 1))
{
successCount++;
}
else
{
errors.Add($"[{i}]: {elemMessage}");
}
}
so.ApplyModifiedProperties();
if (errors.Count > 0)
{
message = $"Set {successCount}/{jArray.Count} elements. Errors: {string.Join("; ", errors)}";
return successCount > 0; // Partial success
}
message = $"Set array with {jArray.Count} elements.";
return true;
}
// Phase 3.2: Handle bulk object mapping - JObject value for Generic (struct/class) properties
if (prop.propertyType == SerializedPropertyType.Generic && !prop.isArray && valueToken is JObject jObj)
{
int successCount = 0;
var errors = new List<string>();
var so = prop.serializedObject;
foreach (var kvp in jObj)
{
string childPath = prop.propertyPath + "." + kvp.Key;
var childProp = so.FindProperty(childPath);
if (childProp == null)
{
errors.Add($"Property not found: {kvp.Key}");
continue;
}
if (TrySetValueRecursive(childProp, kvp.Value, out string childMessage, depth + 1))
{
successCount++;
}
else
{
errors.Add($"{kvp.Key}: {childMessage}");
}
}
so.ApplyModifiedProperties();
if (errors.Count > 0)
{
message = $"Set {successCount}/{jObj.Count} fields. Errors: {string.Join("; ", errors)}";
return successCount > 0; // Partial success
}
message = $"Set struct/class with {jObj.Count} fields.";
return true;
}
// ObjectReference - delegate to shared handler
if (prop.propertyType == SerializedPropertyType.ObjectReference)
{
if (!ComponentOps.SetObjectReference(prop, valueToken, out string refError))
{
message = refError;
return false;
}
message = prop.objectReferenceValue == null
? "Cleared reference."
: $"Set reference to '{prop.objectReferenceValue.name}'.";
return true;
}
// Supported Types: Integer, Boolean, Float, String, Enum, Vector2, Vector3, Vector4, Color
// Using shared helpers from ParamCoercion and VectorParsing
switch (prop.propertyType)
{
case SerializedPropertyType.Integer:
if (valueToken == null || valueToken.Type == JTokenType.Null)
{
message = "Expected integer value.";
return false;
}
if (valueToken.Type != JTokenType.Integer && valueToken.Type != JTokenType.Float
&& !long.TryParse(valueToken.ToString(), out _))
{
message = "Expected integer value.";
return false;
}
if (prop.type == "long")
prop.longValue = ParamCoercion.CoerceLong(valueToken, 0);
else
prop.intValue = ParamCoercion.CoerceInt(valueToken, 0);
message = prop.type == "long" ? "Set long." : "Set int.";
return true;
case SerializedPropertyType.Boolean:
// Use ParamCoercion for robust bool parsing (handles "true", "1", "yes", etc.)
if (valueToken == null || valueToken.Type == JTokenType.Null)
{
message = "Expected boolean value.";
return false;
}
bool boolVal = ParamCoercion.CoerceBool(valueToken, false);
// Verify it actually looked like a bool
if (valueToken.Type != JTokenType.Boolean)
{
string strVal = valueToken.ToString().Trim().ToLowerInvariant();
if (strVal != "true" && strVal != "false" && strVal != "1" && strVal != "0" &&
strVal != "yes" && strVal != "no" && strVal != "on" && strVal != "off")
{
message = "Expected boolean value.";
return false;
}
}
prop.boolValue = boolVal;
message = "Set bool.";
return true;
case SerializedPropertyType.Float:
// Use ParamCoercion for robust float parsing
float floatVal = ParamCoercion.CoerceFloat(valueToken, float.NaN);
if (float.IsNaN(floatVal))
{
message = "Expected float value.";
return false;
}
prop.floatValue = floatVal;
message = "Set float.";
return true;
case SerializedPropertyType.String:
prop.stringValue = valueToken.Type == JTokenType.Null ? null : valueToken.ToString();
message = "Set string.";
return true;
case SerializedPropertyType.Enum:
return TrySetEnum(prop, valueToken, out message);
case SerializedPropertyType.Vector2:
// Use VectorParsing for Vector2
var v2 = VectorParsing.ParseVector2(valueToken);
if (v2 == null)
{
message = "Expected Vector2 (array or object).";
return false;
}
prop.vector2Value = v2.Value;
message = "Set Vector2.";
return true;
case SerializedPropertyType.Vector3:
// Use VectorParsing for Vector3
var v3 = VectorParsing.ParseVector3(valueToken);
if (v3 == null)
{
message = "Expected Vector3 (array or object).";
return false;
}
prop.vector3Value = v3.Value;
message = "Set Vector3.";
return true;
case SerializedPropertyType.Vector4:
// Use VectorParsing for Vector4
var v4 = VectorParsing.ParseVector4(valueToken);
if (v4 == null)
{
message = "Expected Vector4 (array or object).";
return false;
}
prop.vector4Value = v4.Value;
message = "Set Vector4.";
return true;