You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在HoloLens 2上实现Unity应用点击关闭按钮退出功能

HoloLens 2 应用关闭异常解决方案(MRTK 2 + Unity)

问题原因

HoloLens 2 基于 UWP 平台,Unity 原生的 Application.Quit() API 不适用于 UWP 应用的生命周期管理,直接调用会触发异常。UWP 应用有专属的退出机制,必须通过系统 API 实现。

正确实现方式

  1. 引入UWP命名空间
    在脚本顶部添加平台条件编译的命名空间引用,避免编辑器报错:
#if UNITY_WSA && !UNITY_EDITOR
using Windows.ApplicationModel.Core;
using Windows.UI.Core;
#endif
  1. 编写跨平台关闭方法
    实现同时兼容编辑器和HoloLens设备的关闭逻辑:
using UnityEngine;

public class AppCloseHandler : MonoBehaviour
{
    public void CloseApplication()
    {
#if UNITY_WSA && !UNITY_EDITOR
        // UWP平台下,通过CoreApplication在UI线程执行退出操作
        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            CoreApplication.Exit();
        });
#else
        // 编辑器/其他平台使用Unity原生方法
        Application.Quit();
#endif
    }
}
  1. 绑定到MRTK按钮
  • 将脚本挂载到场景中的任意GameObject上
  • 选中MRTK的Interactable按钮组件,在OnClick事件列表中添加该脚本的CloseApplication方法
  • 确保按钮已配置碰撞体和正确的交互设置(比如启用手部射线交互)

注意事项

  • 部署前检查Unity Player Settings:确认UWP平台的"Target Device"设置为HoloLens,权限配置无冲突
  • 测试时,编辑器中点击按钮会关闭Unity编辑器;部署到HoloLens 2设备后,点击按钮可正常退出应用

内容的提问来源于stack exchange,提问作者Meghana G T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 17:42:10