Home > Software engineering >  c# script terminates unexpectedly after merge in UnityEditor
c# script terminates unexpectedly after merge in UnityEditor

Time:11-17

[MenuItem("bat/merge")]
public static void merge(){
    Process p = GetNewProcess("git_merge.bat")
    p.Exited =(obj,e)=>{
        if(p.ExitCode == -1) return;
        Debug.Log(p.ExitCode);
        ...
        // following code would not run
        Debug.Log(PlayerSettings.bundleVersion);
        if(Application.isPlaying)...
    }
    p.Start();
}

There is no exception being thrown. It seems like if I try to get some Editor-related value, the process will be terminated.

CodePudding user response:

Most of Unity API is only accessible from the Unity main thread.

The event p.Exited is most likely not invoked on that thread but async.

=> You will need to have a "Main thread dispatcher" running in the Unity main thread and awaiting your result

Usually you do this on runtime using a MonoBehaviour but in this case here it is an editor script so you could e.g. go for

[MenuItem("bat/merge")]
public static void merge()
{
    Process p = GetNewProcess("git_merge.bat");
    p.Exited  = (obj, e) =>
    {
        // Instead of directly executing your code you instead 
        // move it into a callback function
        void MainThreadCallback()
        {
            // Since you want to execute this only once remove the callback
            EditorApplication.update -= MainThreadCallback;

            // I would put this first just for debugging reasons ;)
            Debug.Log(p.ExitCode);
            if (p.ExitCode == -1) return;

            Debug.Log(PlayerSettings.bundleVersion);

            if (Application.isPlaying)
            {
                //...
            }
        }

        // Then you tell the editor to call your callback 
        // with the next global editor update
        EditorApplication.update  = MainThreadCallback;
    };
    p.Start();
}
  • Related