4 using System.Text.RegularExpressions;
8 namespace Essentials.EditorTweaks
25 [MenuItem(
"Assets/Update class name to match file name",
false, 19)]
26 private static void UpdateClassNameToMatchFile()
29 MonoScript[] scripts = Selection.GetFiltered<MonoScript>(SelectionMode.Assets);
31 if (scripts.IsNullOrEmpty() || scripts.Length != 1)
33 Debug.LogError(
"One script file must be selected to update the class contained in it.");
37 MonoScript script = scripts[0];
38 int selectedScriptID = script.GetInstanceID();
40 string newClassName = script.name;
42 ReplaceClassName(newClassName, AssetDatabase.GetAssetPath(selectedScriptID));
49 [MenuItem(
"Assets/Update class name to match file name",
true, 19)]
50 private static bool IsSingleScriptSelected()
53 MonoScript[] scripts = Selection.GetFiltered<MonoScript>(SelectionMode.Assets);
56 return !scripts.IsNullOrEmpty() && scripts.Length == 1;
64 private static void ReplaceClassName(
string newClassName,
string scriptPath)
68 string[] fileText = File.ReadAllLines(scriptPath);
70 for (
int i = 0; i < fileText.Length; i++)
73 if (!Regex.IsMatch(fileText[i],
@"\bclass\b"))
76 if (Regex.IsMatch(fileText[i],
"\\b" + newClassName +
"\\b"))
78 Debug.Log($
"Class in file '{scriptPath}' already has the same name as the file ('{newClassName}').");
84 const string regexPattern =
@"(?<=class )\w+";
85 fileText[i] = Regex.Replace(fileText[i], regexPattern, newClassName);
86 File.WriteAllLines(scriptPath, fileText);
88 AssetDatabase.Refresh(ImportAssetOptions.Default);
89 Debug.Log($
"Class in file '{scriptPath}' has been successfully renamed to '{newClassName}'.");
92 catch (Exception exception)
94 Debug.Log($
"Something went wrong: {exception.Message}");
100 #region DuplicateAsset
105 [MenuItem(
"Assets/Duplicate",
false, 19)]
106 private static void DuplicateAsset()
108 EditorWindow.focusedWindow.SendEvent (EditorGUIUtility.CommandEvent (
"Duplicate"));
115 [MenuItem(
"Assets/Duplicate",
true, 19)]
116 private static bool AreAssetsSelected()
118 return Selection.assetGUIDs.Length > 0;