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


相关推荐
Maynor99614 分钟前
「原子弹爆炸」级别:Astra 复刻游戏合集(含实机截图)
java·linux·运维·数据库·gpt·游戏
远离UE413 小时前
UE5 高性能 实时 玻璃破碎系统
ue5
远离UE41 天前
UE5 多线程 与 异步 并行
ue5
wind100322 天前
DLSS5 开启保姆级教程:RTX20/30/40 显卡通用 鸣潮 / 异环 / 绝区零全适配
游戏·电脑·英伟达·dlss·鸣潮
全速向光2 天前
JoiPlay 模拟器:在手机上畅玩你所热爱的独立游戏
游戏·智能手机
yangmu32033 天前
《黎明行者之血》MOD整合包保姆级安装与使用指南
游戏·游戏程序
Jgch223 天前
出海Facebook广告账户怎么选?
游戏·facebook
长脖鹿Johnny3 天前
游戏输入系统框架设计(三):网络输入权威与可验证性
网络·游戏·游戏开发·架构设计·输入系统·网络同步
谈资一本本3 天前
电脑全能修复大师 Gilisoft Total Repair,智能检测修复系统、应用、游戏问题!DLL、DirectX、.NET运行库损坏修复+缺失自动补齐!
游戏·电脑·.net
程序员-Benothing3 天前
H3 Max开放世界RPG:AI原生游戏,从“能生成“到“能玩“差了多远
游戏·ai-native