UE5 - 制作游戏中切换窗口后游戏自动暂停功能

个人学习笔记归档;

玩家在游戏运行时,比如在窗口模式下,当切换到其它程序的窗口,游戏自动暂停的逻辑,需要借助C++的基类来实现,方法为以下步骤;

添加C++类必须在UE中添加,这样新的C++类才能保证环境配置正确:

新的类继承GameViewportClient:

设置好路径和类名即可:

然后直接打开VS:

把建立的MyGameViewportClient.h内容修改为:

复制代码
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "Engine/GameViewportClient.h"
#include "MyGameViewportClient.generated.h"

DECLARE_DYNAMIC_MULTICAST_DELEGATE(FOnWindowFocusChanged);

/**
 * 
 */
UCLASS()
class TESTCODEPROJECT_API UMyGameViewportClient : public UGameViewportClient
{
    GENERATED_BODY()
    
    public:
    UPROPERTY(BlueprintAssignable, Category = "Window Focus")
    FOnWindowFocusChanged OnWindowLostFocus;

    UPROPERTY(BlueprintAssignable, Category = "Window Focus")
    FOnWindowFocusChanged OnWindowReceivedFocus;

    UFUNCTION(BlueprintPure, Category = "Window Focus")
    static UMyGameViewportClient* GetMyGameViewportClient();

protected:
    virtual void LostFocus(FViewport* InViewport) override;
    virtual void ReceivedFocus(FViewport* InViewport) override;

};

把MyGameViewportClient.cpp内容修改为:

复制代码
// Fill out your copyright notice in the Description page of Project Settings.

#include "System/MyGameViewportClient.h"
#include "Engine/Engine.h"

void UMyGameViewportClient::LostFocus(FViewport* InViewport)
{
    Super::LostFocus(InViewport);
    OnWindowLostFocus.Broadcast();
}

void UMyGameViewportClient::ReceivedFocus(FViewport* InViewport)
{
    Super::ReceivedFocus(InViewport);
    OnWindowReceivedFocus.Broadcast();
}

UMyGameViewportClient* UMyGameViewportClient::GetMyGameViewportClient()
{
    if (GEngine && GEngine->GameViewport)
    {
        // 获取引擎当前的 Viewport 并转换成我们自己的类
        return Cast<UMyGameViewportClient>(GEngine->GameViewport);
    }
    return nullptr;
}

保存源码后编译,注意只用关注仅生成列表中是否有错误:

这样就可以通过获取My Game Viewport Client绑定相关事件,在游戏运行时,比如在窗口模式下,当玩家切换到其它程序的窗口,游戏自动暂停等逻辑:


相关推荐
java_logo9 小时前
Docker 部署 EmulatorJS:轻松搭建浏览器复古游戏平台
游戏·docker·容器·复古游戏·轩辕镜像·emulatorjs·红白机
AI小百科2 天前
AI 进游戏:游戏里的 NPC 开始有自己的性格
人工智能·游戏·ai
云-缩影2 天前
文生图技术落地:从广告到游戏,哪些场景真的能用
人工智能·游戏
hkNaruto3 天前
【AI】游戏大模型智能体OODA过程记忆问题解决方案:AgenticSTS 有界记忆契约:技术分析与流水线改造操作手册
人工智能·游戏·机器学习
Zhichao_973 天前
【UE5.8】VS2026安装
ue5
tealcwu3 天前
【Unity基础】为什么游戏需要物理按键映射?从 Unity Input Manager 到跨引擎输入设计
java·游戏·unity
沐飞工具箱3 天前
游戏、漫画、视频里的外语怎么实时翻译?从 OCR + AI 原理聊聊 VoriTrans 屏幕翻译
人工智能·游戏·实时互动·音视频·自动翻译
DolitD3 天前
UE像素流与云渲染技术方案对比分析
3d·云原生·ue5·云计算·图形渲染
小小数媒成员4 天前
UGUI原理(一)
开发语言·游戏·unity·游戏引擎
揽星河..4 天前
【C语言】扫雷游戏
c语言·算法·游戏