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


相关推荐
远离UE413 小时前
UE5 SF_VertexShader 如何使用
ue5
电子云与长程纠缠16 小时前
UE5 Lyra PocketWorld进行3D内容UI预览 - 上
开发语言·学习·3d·ue5·游戏引擎
玖玥拾16 小时前
Unity3D RPG 入门项目(八)游戏设置面板、帧率控制、快捷技能药品栏、技能解锁系统
游戏·3d·unity·游戏引擎
电子云与长程纠缠19 小时前
UE5 Lyra PocketWorld进行3D内容UI预览 - 下
开发语言·学习·游戏·ui·ue5
远离UE42 天前
UE5 GPU内部异步
ue5
1204157137 肖哥2 天前
UE5 PCG PCGBlueprintElement简介
ue5
dong1326972 天前
UE5FPS游戏开发教程(四)
ue5
dong1326972 天前
UE5FPS游戏开发教程(三)
ue5
日月云棠2 天前
UE5源码分析之Editor——AnimationBlueprintLibrary模块全面分析
ue5
远离UE43 天前
UE5 ECS 原理
ue5