gkngkc / UnityStandaloneFileBrowser

A native file browser for unity standalone platforms
MIT License
2.01k stars 317 forks source link

How to start a FilePicker in separate thread/Coroutine? #134

Open ClmnsRck opened 9 months ago

ClmnsRck commented 9 months ago

Opening the file picker panel halts the entire unity application, even if started in Coroutine or while using OpenFilePickerAsync().

Is it possible to open a instance that is decoupled from the rest of the application?

TobiasWehrum commented 4 months ago

This apparently only happens in Windows. Unless you want to directly change code inside UnityStandaloneFileBrowser, you have treat calls differently on Windows.

Here is my solution for it:

void ShowDialog(string title)
{
#if PLATFORM_STANDALONE_WIN
    Task.Run(() => StandaloneFileBrowser.OpenFilePanel(title, "", "", false)).ContinueWithOnMainThread(OnCallbackTask);
#else
    StandaloneFileBrowser.OpenFilePanelAsync(title, "", "", false, OnCallback);
#endif
}

private void OnCallbackTask(Task<string[]> task)
{
    if (task.Exception != null)
    {
        // Some kind of exception happened in OpenFilePanel, somehow. Treat it however you see fit here.
        OnCallback([]);
    }
    else
    {
        OnCallback(task.Result);
    }
}

private void OnCallback(string[] paths)
{
    // Our usual callback
}

Note that it seems that the Unity app cannot close while the file dialog is still open - it will just hang if you press Alt+F4 until the dialog is closed. I haven't found a solution for that yet.