Version: 2021.2

MonoBehaviour.OnApplicationFocus(bool)

切换到手册

参数

hasFocus 如果 GameObject 具有焦点,则为 true,否则为 false。

描述

当玩家获得或失去焦点时,发送给所有 GameObject。

OnApplicationFocus 在应用程序丢失或获得焦点时调用。 使用 Alt + Tab 或 Cmd + Tab 可以将焦点从 Unity 应用程序转移到 另一个桌面应用程序。这会导致该 GameObject 收到 参数设置为 false 的 OnApplicationFocus 调用。当用户切换回 Unity 应用程序时, GameObject 会收到参数设置为 true 的 OnApplicationFocus

OnApplicationFocus 可以作为协同程序使用 - 在函数中使用 yield 语句即可。 以这种方式实现时,将在初始帧期间对其计算两次: 第一次是早期通知,第二次在正常的协同程序更新步骤期间进行。

On Android, when the on-screen keyboard is enabled, it causes an OnApplicationFocus( false ) event. If you press Home when the keyboard is enabled, the OnApplicationPause() event is called instead of the OnApplicationFocus() event.

Note: If the Editor is in Play mode, OnApplicationFocus is called when the Game view loses or gains focus. If an external application (meaning an application other than Unity) has focus, and you click a different Editor tab, ::OnApplicationFocus is called twice in one frame. The first time, OnApplicationFocus is called with hasFocus set to true because the Game view regains focus when Unity regains focus. The second time, OnApplicationFocus is called with hasFocus set to false because the Game view loses focus to the Editor tab that was clicked.

To minimize the number of times OnApplicationFocus is called when the Editor is in Play mode, and you are using the rest of the Editor, drag the Game view into a floating window.

using UnityEngine;

public class AppPaused : MonoBehaviour { bool isPaused = false;

void OnGUI() { if (isPaused) GUI.Label(new Rect(100, 100, 50, 30), "Game paused"); }

void OnApplicationFocus(bool hasFocus) { isPaused = !hasFocus; }

void OnApplicationPause(bool pauseStatus) { isPaused = pauseStatus; } }