|
| 1 | +using System; |
| 2 | +using UnityEngine; |
| 3 | +using UnityEditor; |
| 4 | +using Newtonsoft.Json.Linq; |
| 5 | +using McpUnity.Unity; |
| 6 | +using McpUnity.Utils; |
| 7 | + |
| 8 | +namespace McpUnity.Tools |
| 9 | +{ |
| 10 | + /// <summary> |
| 11 | + /// Tool for creating prefabs with optional MonoBehaviour scripts |
| 12 | + /// </summary> |
| 13 | + public class CreatePrefabTool : McpToolBase |
| 14 | + { |
| 15 | + public CreatePrefabTool() |
| 16 | + { |
| 17 | + Name = "create_prefab"; |
| 18 | + Description = "Creates a prefab with optional MonoBehaviour script and serialized field values"; |
| 19 | + } |
| 20 | + |
| 21 | + /// <summary> |
| 22 | + /// Execute the CreatePrefab tool with the provided parameters |
| 23 | + /// </summary> |
| 24 | + /// <param name="parameters">Tool parameters as a JObject</param> |
| 25 | + public override JObject Execute(JObject parameters) |
| 26 | + { |
| 27 | + // Extract parameters |
| 28 | + string scriptName = parameters["scriptName"]?.ToObject<string>(); |
| 29 | + string prefabName = parameters["prefabName"]?.ToObject<string>(); |
| 30 | + JObject fieldValues = parameters["fieldValues"]?.ToObject<JObject>(); |
| 31 | + |
| 32 | + // Validate required parameters |
| 33 | + if (string.IsNullOrEmpty(prefabName)) |
| 34 | + { |
| 35 | + return McpUnitySocketHandler.CreateErrorResponse( |
| 36 | + "Required parameter 'prefabName' not provided", |
| 37 | + "validation_error" |
| 38 | + ); |
| 39 | + } |
| 40 | + |
| 41 | + // Create a temporary GameObject |
| 42 | + GameObject tempObject = new GameObject(prefabName); |
| 43 | + |
| 44 | + // Add component if provided |
| 45 | + if (!string.IsNullOrEmpty(scriptName)) |
| 46 | + { |
| 47 | + try |
| 48 | + { |
| 49 | + // Add component |
| 50 | + Component component = AddComponent(tempObject, scriptName); |
| 51 | + |
| 52 | + // Apply field values if provided and component exists |
| 53 | + ApplyFieldValues(fieldValues, component); |
| 54 | + } |
| 55 | + catch (Exception ex) |
| 56 | + { |
| 57 | + return McpUnitySocketHandler.CreateErrorResponse( |
| 58 | + $"Failed to add component '{scriptName}' to GameObject", |
| 59 | + "component_error" |
| 60 | + ); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + // For safety, we'll create a unique name if prefab already exists |
| 65 | + int counter = 1; |
| 66 | + string prefabPath = $"{prefabName}.prefab"; |
| 67 | + while (AssetDatabase.AssetPathToGUID(prefabPath) != "") |
| 68 | + { |
| 69 | + prefabPath = $"{prefabName}_{counter}.prefab"; |
| 70 | + counter++; |
| 71 | + } |
| 72 | + |
| 73 | + // Create the prefab |
| 74 | + GameObject prefab = PrefabUtility.SaveAsPrefabAsset(tempObject, prefabPath); |
| 75 | + |
| 76 | + // Clean up temporary object |
| 77 | + UnityEngine.Object.DestroyImmediate(tempObject); |
| 78 | + |
| 79 | + // Refresh the asset database |
| 80 | + AssetDatabase.Refresh(); |
| 81 | + |
| 82 | + // Log the action |
| 83 | + McpLogger.LogInfo($"Created prefab '{prefab.name}' at path '{prefabPath}' from script '{scriptName}'"); |
| 84 | + |
| 85 | + // Create the response |
| 86 | + return new JObject |
| 87 | + { |
| 88 | + ["success"] = true, |
| 89 | + ["type"] = "text", |
| 90 | + ["message"] = $"Successfully created prefab '{prefab.name}' at path '{prefabPath}'", |
| 91 | + ["prefabPath"] = prefabPath |
| 92 | + }; |
| 93 | + } |
| 94 | + |
| 95 | + private Component AddComponent(GameObject gameObject, string scriptName) |
| 96 | + { |
| 97 | + // Find the script type |
| 98 | + Type scriptType = Type.GetType($"{scriptName}, Assembly-CSharp"); |
| 99 | + if (scriptType == null) |
| 100 | + { |
| 101 | + // Try with just the class name |
| 102 | + scriptType = Type.GetType(scriptName); |
| 103 | + } |
| 104 | + |
| 105 | + if (scriptType == null) |
| 106 | + { |
| 107 | + // Try to find the type using AppDomain |
| 108 | + foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) |
| 109 | + { |
| 110 | + scriptType = assembly.GetType(scriptName); |
| 111 | + if (scriptType != null) |
| 112 | + break; |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + // Throw an error if the type was not found |
| 117 | + if (scriptType == null) |
| 118 | + { |
| 119 | + return null; |
| 120 | + } |
| 121 | + |
| 122 | + // Check if the type is a MonoBehaviour |
| 123 | + if (!typeof(MonoBehaviour).IsAssignableFrom(scriptType)) |
| 124 | + { |
| 125 | + return null; |
| 126 | + } |
| 127 | + |
| 128 | + return gameObject.AddComponent(scriptType); |
| 129 | + } |
| 130 | + |
| 131 | + private void ApplyFieldValues(JObject fieldValues, Component component) |
| 132 | + { |
| 133 | + // Apply field values if provided and component exists |
| 134 | + if (fieldValues == null || fieldValues.Count == 0) |
| 135 | + { |
| 136 | + return; |
| 137 | + } |
| 138 | + |
| 139 | + Undo.RecordObject(component, "Set field values"); |
| 140 | + |
| 141 | + foreach (var property in fieldValues.Properties()) |
| 142 | + { |
| 143 | + // Get the field/property info |
| 144 | + var fieldInfo = component.GetType().GetField(property.Name, |
| 145 | + System.Reflection.BindingFlags.Public | |
| 146 | + System.Reflection.BindingFlags.NonPublic | |
| 147 | + System.Reflection.BindingFlags.Instance); |
| 148 | + |
| 149 | + if (fieldInfo != null) |
| 150 | + { |
| 151 | + // Set field value |
| 152 | + object value = property.Value.ToObject(fieldInfo.FieldType); |
| 153 | + fieldInfo.SetValue(component, value); |
| 154 | + } |
| 155 | + else |
| 156 | + { |
| 157 | + // Try property |
| 158 | + var propInfo = component.GetType().GetProperty(property.Name, |
| 159 | + System.Reflection.BindingFlags.Public | |
| 160 | + System.Reflection.BindingFlags.NonPublic | |
| 161 | + System.Reflection.BindingFlags.Instance); |
| 162 | + |
| 163 | + if (propInfo != null && propInfo.CanWrite) |
| 164 | + { |
| 165 | + object value = property.Value.ToObject(propInfo.PropertyType); |
| 166 | + propInfo.SetValue(component, value); |
| 167 | + } |
| 168 | + } |
| 169 | + } |
| 170 | + } |
| 171 | + } |
| 172 | +} |
0 commit comments