using UnityEngine; using UnityEditor; public class ReplaceWithPrefabWindow : EditorWindow { private GameObject _prefab; private bool inheritPosition = true; private bool inheritScale = true; private bool inheritRotation = true; [MenuItem("Tools/Replace Selected with Prefab")] static void ShowWindow() { GetWindow("Replace With Prefab"); } private void OnGUI() { GUILayout.Label("Select Prefab to Replace With", EditorStyles.boldLabel); _prefab = (GameObject)EditorGUILayout.ObjectField("Prefab", _prefab, typeof(GameObject), false); inheritPosition = EditorGUILayout.Toggle("Inherit Position", inheritPosition); inheritRotation = EditorGUILayout.Toggle("Inherit Rotation", inheritRotation); inheritScale = EditorGUILayout.Toggle("Inherit Scale", inheritScale); if (GUILayout.Button("Replace")) { ReplaceSelectedObjects(); } } private void ReplaceSelectedObjects() { if (_prefab == null) { Debug.LogWarning("No prefab selected."); return; } if (Selection.gameObjects.Length == 0) { Debug.LogWarning("No objects selected."); return; } GameObject[] selectedObjects = Selection.gameObjects; foreach (GameObject selectedObject in selectedObjects) { // 创建新对象并记录到撤销历史 GameObject newObject = (GameObject)PrefabUtility.InstantiatePrefab(_prefab); Undo.RegisterCreatedObjectUndo(newObject, "Replace with Prefab"); newObject.transform.SetParent(selectedObject.transform.parent); // 继承属性 if (inheritPosition) newObject.transform.position = selectedObject.transform.position; if (inheritRotation) newObject.transform.rotation = selectedObject.transform.rotation; if (inheritScale) newObject.transform.localScale = selectedObject.transform.localScale; // 删除原始对象并记录到撤销历史 Undo.DestroyObjectImmediate(selectedObject); } } }