Force Unity to recompile scripts

Unity 2019.3 introduced public editor API to force scripts recompilation: it’s UnityEditor.Compilation.CompilationPipeline.RequestScriptCompilation method. Tested it with hooking to assembly compilation started/finished events and this method indeed recompiles all scripts in the project.


For Unity versions from Unity 2017.1 to Unity 2019.2 can call UnityEditor.Scripting.ScriptCompilation.EditorCompilationInterface.DirtyAllScripts via reflection. DirtyAllScripts is the method Unity 2019.3 calls internally from RequestScriptCompilation method (see reference). Sadly for Unity versions older than 2017.1 I’m not sure DirtyAllScripts is present since Unity C# reference has no source code for that Unity versions.


Simple editor window to force scripts recompilation on button click (tested with Unity 2019.3.0f6 and Unity 2017.1.1f1):

using UnityEditor;
#if UNITY_2019_3_OR_NEWER
using UnityEditor.Compilation;
#elif UNITY_2017_1_OR_NEWER
using System.Reflection;
#endif
using UnityEngine;

namespace PumpEditor
{
    public class CompilationWindow : EditorWindow
    {
        [MenuItem("Window/Pump Editor/Compilation")]
        private static void ShowWindow()
        {
            var window = EditorWindow.GetWindow<CompilationWindow>();
            window.titleContent = new GUIContent("Compilation");
            window.Show();
        }

        private void OnGUI()
        {
            if (GUILayout.Button("Request Script Compilation"))
            {
#if UNITY_2019_3_OR_NEWER
                CompilationPipeline.RequestScriptCompilation();
#elif UNITY_2017_1_OR_NEWER
                var editorAssembly = Assembly.GetAssembly(typeof(Editor));
                var editorCompilationInterfaceType = editorAssembly.GetType("UnityEditor.Scripting.ScriptCompilation.EditorCompilationInterface");
                var dirtyAllScriptsMethod = editorCompilationInterfaceType.GetMethod("DirtyAllScripts", BindingFlags.Static | BindingFlags.Public);
                dirtyAllScriptsMethod.Invoke(editorCompilationInterfaceType, null);
#endif
            }
        }
    }
}

THIS is exactly what I was looking for! Thank you! :D

–