Skip to content

Instantly share code, notes, and snippets.

@eriseven
Created February 18, 2025 09:24
Show Gist options
  • Save eriseven/498265103b17ec6a73bc389f976758e4 to your computer and use it in GitHub Desktop.
Save eriseven/498265103b17ec6a73bc389f976758e4 to your computer and use it in GitHub Desktop.
public static class MonoBehaviourExtensions
{
#if UNITY_EDITOR
// [UnityEditor.MenuItem("CONTEXT/MonoBehaviour/Change Script")]
// [UnityEditor.MenuItem("CONTEXT/AVGFramework.Runtime.UI.AVGImage/Change Script")]
[UnityEditor.MenuItem("CONTEXT/AVGImage/Change Script")]
public static void ChangeScript(MenuCommand command)
{
if (command.context == null) return;
var monoBehaviour = command.context as MonoBehaviour;
var monoScript = MonoScript.FromMonoBehaviour(monoBehaviour);
var scriptPath = AssetDatabase.GetAssetPath(monoScript);
var directoryPath = new FileInfo(scriptPath).Directory?.FullName;
// Allow the user to select which script to replace with
var newScriptPath = EditorUtility.OpenFilePanel("Select replacement script", directoryPath, "cs");
newScriptPath = newScriptPath.Replace('\\', '/');
// Don't log anything if they cancelled the window
if (string.IsNullOrEmpty(newScriptPath)) return;
// Load the selected asset
var relativePath = newScriptPath.Replace(Application.dataPath.Replace("Assets", ""), "");//"Assets\\" + Path.GetRelativePath(Application.dataPath, newScriptPath);
Debug.Log("newScriptPath: " + relativePath);
// var chosenTextAsset = AssetDatabase.LoadAssetAtPath<TextAsset>(relativePath);
var chosenTextAsset = AssetDatabase.LoadAssetAtPath(relativePath, typeof(Object));
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();
}
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment