Hello!
We currently embed the Unity exe into our parent WPF app with the command line argument -parentHWND.
Because of reasons, we would like to switch to embedding Unity as a DLL directly, by loading the UnityPlayer.dll from code into our host application. Loading, embedding, and starting a Unity scene with the DLL works.
But:
We have tremendous difficulties with unloading/closing Unity and closing (only) the window where it is embedded.
A short explanation about the setup we want to have in the end:
The host application has a main window. Then the user can open another window (let’s call it ‘3D window’) that, among other WPF elements, displays the Unity frame. The user needs to be able to close and reopen the 3D window, without the main window closing/ending. Booting Unity from scratch, every time the 3D window is opened, is OK.
We currently use Unity v. 2021.3.9f1 (LTS).
These are the things we tried and the problems we encountered:
First, we tried Unity’s Application.Unload(), but found out – after some time – that it only seems to be supported for iOS and UWP host applications.
Problem 1: Our host application is a WPF application, so Unload() does exactly nothing.
Secondly, we tried Unity’s Application.Quit(), but:
Problem 2: Quit() takes down the whole host application with it – not only the 3D window, but also the main window.
Thirdly, we tried unloading the DLL manually using FreeLibrary(IntPtr hModule).
Interestingly, if we call FreeLibrary() exactly four times, Unity actually closes.
Problem 3: Why four times? Unity seems to increase its reference counter internally when being loaded as DLL, but we have no insight into what actually happens under the hood.
Problem 4: Unloading yields the same behaviour as Application.Quit(): it takes down the whole host application with it.
Problem 5 (Bonus): We cannot close the 3D window with the red Windows X on the top right. Nothing happens, if we click it.
Main question:
Are there any alternatives to Application.Unload()/.Quit() when embedding Unity as DLL in a WPF host application?
Or generally, is it even possible to stop/unload/terminate the running Unity DLL, without killing the whole application?
Any help is greatly appreciated!
Greetings,
Christian