本页说明如何使用“Unity 用作库”功能将 Unity 运行时库集成到 Windows 和通用 Windows 平台 (UWP) 应用程序中。
使用此功能可以在应用程序中包含 Unity 支持的功能(例如 3D/2D 实时渲染、AR 体验、3D 模型交互或 2D 迷你游戏)。Unity 运行时库公开了多种控件来管理何时以及如何在应用程序中加载、激活和卸载内容。
使用 UWP XAML 项目输出类型可方便创建嵌入了 Unity 的 UWP 项目。生成的 Visual Studio 项目是常规 XAML UWP 项目,其中包含 SwapChainPanel 设置,可用于加载 Unity 项目。可以使用任何其他非 Unity 应用程序业务逻辑来扩展或替换该项目。
使用 SwapchainPanel 时,您可能需要在其他元素上渲染。这使您可以在其他非 Unity 应用程序内容上渲染具有透明背景的小对象。为此,请启用 PlayerSettings.WSA-transparentSwapchain
选项。
Unity 采用过程中加载时,可以使用 Application.Unload
来卸载 Unity 引擎以回收资源。
在 Windows 上,可以通过两种不同方式将 Unity 嵌入到应用程序中。
最简单选项是将 Unity 作为外部进程从应用程序启动,并指定一个窗口让 Unity 在该窗口中使用 -parentHWND
命令行参数进行初始化和渲染。
第二个选项是将 Unity 嵌入现有进程中。为此,请将 Unity 构建到 UnityPlayer.dll
中,从而可由任何 Win32 应用程序直接加载。入口点签名为:
extern "C" UNITY_API int UnityMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd);
可以使用 lpCmdLine
将任何命令行参数传递给 Unity 以控制分辨率、作业线程、父级 HWND 等。这使您能够在进程内运行 Unity。Unity 不在视图中的时候,您可以使用 Application.Unload
来回收它所用的资源。
由另一个应用程序托管时,Unity 不能控制运行时生命周期,因此可能无法在所有情况下都奏效。已知限制包括:
–
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.