Small threading problem when starting a new Unity instance from running Unity app

I’ve build a Unity application which launches other projects, such as games. I’m starting those other applications via the C# Process class. Next, I need a callback to know, when the new running process was closed, so that I can perform some UI actions in my main application.

public void RunProject(string path)
{
    try
    {
        Process p = Process.Start(path);
        p.EnableRaisingEvents = true;
        p.Exited += new EventHandler(ProcessExited2);
    }
    catch(Exception e)
    {
        ///
    }
}

private void ProcessExited2(object sender, EventArgs e)
{
    Process p = (Process)sender;
    // Dispose of resources held by the process.
    p.Close();
    RunningInstance = null;

    if(OnProcessExited != null)
        OnProcessExited.Invoke();
}

The above code practically works. I starts another Unity game and when it is closed, OnProcessExited is invoked. However, I guess because Unity isn’t thread safe, I get an exception:

“get_isPlaying can only be called from the main thread.”

I don’t use Application.isPlaying anywhere in my project, so I assume it is called by the new running instance I started via the Process class. I can see that there is a problem, because I have two open Unity processes on separate threads and one is sending a callback to the other, which is not allowed, because the Unity API is not thread safe.

Is there any way to go about this in a better way? Or should this theoretically work and I’m making some other mistake?

Thanks!

Instead of doing anything in ProcessExited2(), you should probably write down the information that it gives you (make local instance copies) and set a flag somewhere, then in your main Update() function, check for that flag, and do the processing that you are presently doing in ProcessExited2().

1 Like

Thanks, I will try that, but so far I don’t see how this is any different. I still need the callback from Unity instance 1 to Unity instance 2, making a local copy doesn’t change the threading issue or does it?

Update() is run in the main thread. From your original error message, it would APPEAR that the callback is NOT run in that same main thread, but this is just speculation.

If the error is coming from something else running not in the main thread, then we have yet a whole other problem, but I am speculating that the callback is simply not running in the main thread, and my fix above might solve that issue.