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

Unity后台运行时如何阻止屏幕保护/闲置计时器启动?

在Unity中后台运行时阻止系统进入闲置状态的方案

Unity自带的Screen.sleepTimeout = SleepTimeout.NeverSleep仅在应用处于前台活动窗口时生效——当应用后台运行(即便仍可见),Windows系统仍会触发屏保或闲置休眠。以下是针对该问题的解决方案,优先提供跨平台实现,附Windows专属方案:

Windows专属方案

Windows系统提供SetThreadExecutionState API,可让应用告知系统当前处于活跃状态,不受前台/后台状态限制。通过C#的P/Invoke即可在Unity中调用该API:

using UnityEngine;
using System.Runtime.InteropServices;

public class WindowsIdlePreventer : MonoBehaviour
{
    [DllImport("kernel32.dll")]
    private static extern uint SetThreadExecutionState(uint esFlags);

    private const uint ES_CONTINUOUS = 0x80000000;
    private const uint ES_SYSTEM_REQUIRED = 0x00000001;
    private const uint ES_DISPLAY_REQUIRED = 0x00000002;

    void Start()
    {
        // 持续阻止系统休眠与屏幕关闭
        SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED);
    }

    void OnApplicationQuit()
    {
        // 恢复系统默认闲置行为
        SetThreadExecutionState(ES_CONTINUOUS);
    }
}

将此脚本挂载到任意持久化GameObject上即可:启动时调用API锁定系统活跃状态,退出时恢复默认设置,无论应用前台/后台均生效。

跨平台方案

针对不同平台,需调用对应系统API或命令行工具,通过Unity的条件编译实现跨平台兼容:

using UnityEngine;
using System.Runtime.InteropServices;

public class CrossPlatformIdlePreventer : MonoBehaviour
{
#if UNITY_WINDOWS
    [DllImport("kernel32.dll")]
    private static extern uint SetThreadExecutionState(uint esFlags);
    
    private const uint ES_CONTINUOUS = 0x80000000;
    private const uint ES_SYSTEM_REQUIRED = 0x00000001;
    private const uint ES_DISPLAY_REQUIRED = 0x00000002;
#elif UNITY_OSX || UNITY_LINUX
    [DllImport("libc")]
    private static extern int system(string command);
#endif

    void Start()
    {
#if UNITY_WINDOWS
        SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED);
#elif UNITY_OSX
        // 使用caffeinate命令阻止系统闲置(需应用具备相应权限)
        system("caffeinate -i &");
#elif UNITY_LINUX
        // 关闭屏幕休眠与DPMS
        system("xset s off; xset -dpms");
#endif
    }

    void OnApplicationQuit()
    {
#if UNITY_WINDOWS
        SetThreadExecutionState(ES_CONTINUOUS);
#elif UNITY_OSX
        // 终止caffeinate进程
        system("pkill caffeinate");
#elif UNITY_LINUX
        // 恢复屏幕休眠设置
        system("xset s on; xset +dpms");
#endif
    }
}

跨平台方案注意事项:

  • macOS:caffeinate命令需要应用拥有系统权限,部分环境下可能需要用户授权;
  • Linux:xset命令依赖X11环境,Wayland桌面环境需改用其他工具(如wl-screenlock相关命令);
  • 命令行方式需确保应用退出时正确清理残留进程,避免影响系统后续行为。

内容的提问来源于stack exchange,提问作者Dogtanian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 12:24:59