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


相关推荐
梦想平凡11 小时前
棋牌游戏技术实战(十三):缓存对局历史时控制容量,命中以后仍然检查成员权限
游戏·缓存
阿阳微客13 小时前
steam游戏搬砖用选品软件照搬就可以么?经验帖
学习·游戏
FairGuard手游加固1 天前
手游加固怎么做?SO、IL2CPP、AssetBundle 与运行时保护详解
安全·游戏·unity
Vex2une1 天前
GRLP游戏运行库合集:一站式解决DLL缺失与启动报错实战指南 | Game Runtime Libraries Package
游戏·vc++运行库·0xc000007b·游戏运行库·dll缺失修复·directx修复·游戏报错解决
tommyjiatong1 天前
SDK游戏盾的工作原理
游戏·网络安全·sdk盾
远离UE42 天前
UE5 Substrate Thin Film 源码拆析
开发语言·javascript·ue5
tianyatest2 天前
魔兽争霸 III 接入大语言模型:基于文件通道的混合式游戏 AI 智能体系统设计与实现
人工智能·游戏·语言模型·war3
开开心心_Every2 天前
黄金价格软件国内外价格实时监控超方便
运维·服务器·游戏·智能手机·pdf·lua·perl
七仔啊3 天前
UE5源码下载及编译
ue5
Zhichao_973 天前
【UE5.8 MCP】接入AI大模型
ue5