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绑定相关事件,在游戏运行时,比如在窗口模式下,当玩家切换到其它程序的窗口,游戏自动暂停等逻辑:


相关推荐
JQweryuiop6 天前
中小型游戏陪练工作室数字化管理实践:基于七彩屋电竞护航小程序订单、履约与绩效系统的落地复盘
大数据·游戏·小程序·架构
曼巴UE56 天前
UE5 客户端 需要的网络同步概念总结(3 )-事件同步 RPC 以及三种调用方式
网络·c++·网络协议·学习·rpc·ue5
乌萨达7 天前
低配电脑玩手游怎么设置?4GB、8GB内存与模拟器选择指南
游戏·电脑·安卓模拟器·雷电模拟器
林川~019 天前
Unity 万能物理检测工具:射线检测 / 范围检测 / 层级过滤 / 编辑器可视化(可直接拿去用)
游戏·unity·c#·射线检测·通用工具
归真仙人9 天前
【UE项目迁移银河麒麟(Linux)局域网会话搜索失败排查】
ue5·ue4·vr·unreal engine·银河麒麟
一孤程10 天前
游戏测试专题第七篇:游戏自动化测试实战
游戏·测试
一孤程10 天前
游戏测试专题第八篇:游戏安全测试与反外挂
游戏·测试
fanfan_hongyun10 天前
UE5.1 应用InWebSocketClient-main 接收websocket信息
ue5
远离UE411 天前
Chaos、WFC 与 FJA 原理与区别笔记
ue5
河南花仙子科技11 天前
小游戏社交裂变功能的高阶设计思路
大数据·科技·游戏