|
| 1 | +// editor tool to replace string from selected GameObject names |
| 2 | + |
| 3 | +using UnityEngine; |
| 4 | +using UnityEditor; |
| 5 | +using UnityEditor.SceneManagement; |
| 6 | + |
| 7 | +namespace UnityLibrary.Tools |
| 8 | +{ |
| 9 | + public class ReplaceCharacterInGameObjectNames : EditorWindow |
| 10 | + { |
| 11 | + private string searchString = "|"; |
| 12 | + private string replaceString = "@"; |
| 13 | + |
| 14 | + [MenuItem("Tools/Replace Characters in GameObject Names")] |
| 15 | + public static void ShowWindow() |
| 16 | + { |
| 17 | + GetWindow<ReplaceCharacterInGameObjectNames>("Replace Characters"); |
| 18 | + } |
| 19 | + |
| 20 | + private void OnGUI() |
| 21 | + { |
| 22 | + GUILayout.Label("Replace Characters in Selected GameObject Names", EditorStyles.boldLabel); |
| 23 | + |
| 24 | + searchString = EditorGUILayout.TextField("Search String", searchString); |
| 25 | + replaceString = EditorGUILayout.TextField("Replace String", replaceString); |
| 26 | + |
| 27 | + int selectedObjectCount = Selection.gameObjects.Length; |
| 28 | + GUILayout.Label($"Selected GameObjects: {selectedObjectCount}", EditorStyles.label); |
| 29 | + |
| 30 | + if (GUILayout.Button("Replace")) |
| 31 | + { |
| 32 | + ReplaceCharacters(); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + private void ReplaceCharacters() |
| 37 | + { |
| 38 | + GameObject[] selectedObjects = Selection.gameObjects; |
| 39 | + |
| 40 | + if (selectedObjects.Length == 0) |
| 41 | + { |
| 42 | + Debug.LogWarning("No GameObjects selected."); |
| 43 | + return; |
| 44 | + } |
| 45 | + |
| 46 | + // Start a new undo group |
| 47 | + Undo.IncrementCurrentGroup(); |
| 48 | + Undo.SetCurrentGroupName("Replace Character in GameObject Names"); |
| 49 | + int undoGroup = Undo.GetCurrentGroup(); |
| 50 | + |
| 51 | + foreach (GameObject obj in selectedObjects) |
| 52 | + { |
| 53 | + if (obj.name.Contains(searchString)) |
| 54 | + { |
| 55 | + Undo.RecordObject(obj, "Replace Character in GameObject Name"); |
| 56 | + obj.name = obj.name.Replace(searchString, replaceString); |
| 57 | + EditorUtility.SetDirty(obj); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + // End the undo group |
| 62 | + Undo.CollapseUndoOperations(undoGroup); |
| 63 | + |
| 64 | + EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); |
| 65 | + |
| 66 | + Debug.Log($"Replaced '{searchString}' with '{replaceString}' in the names of selected GameObjects."); |
| 67 | + } |
| 68 | + } |
| 69 | +} |
0 commit comments