docs.unrealengine.com/5.0/zh-CN/q…
继承自HowRoUMGGameModeBase
继承自HowTo_UMGPlayerController
HowRoUMG.Build.cs
添加:"UMG" 取消PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" });注释
// Copyright Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
public class HowRoUMG : ModuleRules
{
public HowRoUMG(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore" ,"UMG" });
//PrivateDependencyModuleNames.AddRange(new string[] { });
// Uncomment if you are using Slate UI
PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" });
// Uncomment if you are using online features
// PrivateDependencyModuleNames.Add("OnlineSubsystem");
// To include OnlineSubsystemSteam, add it to the plugins section in your uproject file with the Enabled attribute set to true
}
}
HowRoUMGGameModeBase.h
// Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "Blueprint/UserWidget.h"
#include "HowRoUMGGameModeBase.generated.h"
/**
*
*/
UCLASS()
class HOWROUMG_API AHowRoUMGGameModeBase : public AGameModeBase
{
GENERATED_BODY()
public:
/** 移除当前菜单控件,并在指定类(如有)中新建控件。*/
UFUNCTION(BlueprintCallable, Category = "UMG Game")
void ChangeMenuWidget(TSubclassOf<UUserWidget> NewWidgetClass);
protected:
/** 游戏开始时调用。*/
virtual void BeginPlay() override;
/** 游戏开始时,用作菜单的控件类。*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "UMG Game")
TSubclassOf<UUserWidget> StartingWidgetClass;
/** 用作菜单的控件实例。*/
UPROPERTY()
UUserWidget* CurrentWidget;
};
HowRoUMGGameModeBase.cpp
// Copyright Epic Games, Inc. All Rights Reserved.
#include "HowRoUMGGameModeBase.h"
void AHowRoUMGGameModeBase::BeginPlay()
{
Super::BeginPlay();
ChangeMenuWidget(StartingWidgetClass);
}
void AHowRoUMGGameModeBase::ChangeMenuWidget(TSubclassOf<UUserWidget> NewWidgetClass)
{
if (CurrentWidget != nullptr)
{
CurrentWidget->RemoveFromViewport();
CurrentWidget = nullptr;
}
if (NewWidgetClass != nullptr)
{
CurrentWidget = CreateWidget<UUserWidget>(GetWorld(), NewWidgetClass);
if (CurrentWidget != nullptr)
{
CurrentWidget->AddToViewport();
}
}
}
HowTo_UMGPlayerController.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/PlayerController.h"
#include "HowTo_UMGPlayerController.generated.h"
/**
*
*/
UCLASS()
class HOWROUMG_API AHowTo_UMGPlayerController : public APlayerController
{
GENERATED_BODY()
public:
virtual void BeginPlay() override;
};
HowTo_UMGPlayerController.h
#include "HowTo_UMGPlayerController.h"
void AHowTo_UMGPlayerController::BeginPlay()
{
Super::BeginPlay();
SetInputMode(FInputModeGameAndUI()); //FInputModeGameAndUI 是一种用来设置输入模式的数据结构,允许UI与用户输入交互
}