using UnityEditor; using UnityEngine; public class ReplaceGameobjectsEditor : EditorWindow { public GameObject prefabToReplaceWith; // The prefab you want to use as a replacement public string targetTag = ""; // Tag of the GameObjects to replace (leave empty to replace selected) public string targetName = ""; // Name of the GameObjects to replace (leave empty to replace selected) [MenuItem("Tools/Replace GameObjects")] public static void ShowWindow() { GetWindow("Replace GameObjects"); } private void OnGUI() { EditorGUILayout.LabelField("Replace GameObjects with Prefab", EditorStyles.boldLabel); prefabToReplaceWith = (GameObject)EditorGUILayout.ObjectField("Prefab to Replace With", prefabToReplaceWith, typeof(GameObject), false); EditorGUILayout.Space(); EditorGUILayout.LabelField("Target Selection", EditorStyles.boldLabel); targetTag = EditorGUILayout.TagField("Target Tag (Optional)", targetTag); targetName = EditorGUILayout.TextField("Target Name (Optional)", targetName); EditorGUILayout.HelpBox("If both Tag and Name are empty, selected GameObjects in Hierarchy will be replaced.", MessageType.Info); if (GUILayout.Button("Replace!")) { ReplaceObjects(); } } private void ReplaceObjects() { if (prefabToReplaceWith == null) { Debug.LogError("Please assign a Prefab to Replace With."); return; } GameObject[] objectsToReplace; if (!string.IsNullOrEmpty(targetTag)) { objectsToReplace = GameObject.FindGameObjectsWithTag(targetTag); } else if (!string.IsNullOrEmpty(targetName)) { // Find all GameObjects in the scene and filter by name objectsToReplace = FindObjectsOfType(); System.Collections.Generic.List namedObjects = new System.Collections.Generic.List(); foreach (GameObject go in objectsToReplace) { if (go.name == targetName) { namedObjects.Add(go); } } objectsToReplace = namedObjects.ToArray(); } else { objectsToReplace = Selection.gameObjects; // Replace currently selected GameObjects } if (objectsToReplace.Length == 0) { Debug.LogWarning("No GameObjects found to replace based on your criteria or selection."); return; } foreach (GameObject oldGameObject in objectsToReplace) { GameObject newGameObject = (GameObject)PrefabUtility.InstantiatePrefab(prefabToReplaceWith); newGameObject.transform.position = oldGameObject.transform.position; newGameObject.transform.rotation = oldGameObject.transform.rotation; newGameObject.transform.localScale = oldGameObject.transform.localScale; newGameObject.transform.parent = oldGameObject.transform.parent; // Optionally, copy component values if desired and compatible // For example, if both have a Rigidbody and you want to transfer velocity: // Rigidbody oldRb = oldGameObject.GetComponent(); // Rigidbody newRb = newGameObject.GetComponent(); // if (oldRb != null && newRb != null) { newRb.velocity = oldRb.velocity; } DestroyImmediate(oldGameObject); } Debug.Log($"Replaced {objectsToReplace.Length} GameObjects with instances of '{prefabToReplaceWith.name}'."); } }