using System.IO; using UnityEditor; using UnityEngine; namespace NEG.Utils.Editor { public static class MonoBehaviourExtensions { [MenuItem("CONTEXT/MonoBehaviour/Change Script")] public static void ChangeScript(MenuCommand command) { if (command.context == null) return; var monoBehaviour = command.context as MonoBehaviour; var monoScript = MonoScript.FromMonoBehaviour(monoBehaviour); string scriptPath = AssetDatabase.GetAssetPath(monoScript); string directoryPath = new FileInfo(scriptPath).Directory?.FullName; // Allow the user to select which script to replace with string newScriptPath = EditorUtility.OpenFilePanel("Select replacement script", directoryPath, "cs"); // Don't log anything if they cancelled the window if (string.IsNullOrEmpty(newScriptPath)) return; // Load the selected asset string relativePath = "Assets\\" + Path.GetRelativePath(Application.dataPath, newScriptPath); var chosenTextAsset = AssetDatabase.LoadAssetAtPath(relativePath); if (chosenTextAsset == null) { Debug.LogWarning($"Selected script couldn't be loaded ({relativePath})"); return; } Undo.RegisterCompleteObjectUndo(command.context, "Changing component script"); var so = new SerializedObject(monoBehaviour); var scriptProperty = so.FindProperty("m_Script"); so.Update(); scriptProperty.objectReferenceValue = chosenTextAsset; so.ApplyModifiedProperties(); } } }