
1.在HowTo_UMG.Build.cs中 ,写如下代码
- using UnrealBuildTool;
-
- public class HowTo_UMG : ModuleRules
- {
- public HowTo_UMG(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
- }
- }
2.在HowToUMGGameMode.h中声明变量和函数
- #include "CoreMinimal.h"
- #include "GameFramework/GameModeBase.h"
- #include "Blueprint/UserWidget.h"
- #include "HowTo_UMGGameModeBase.generated.h"
-
- /**
- *
- */
- UCLASS()
- class HOWTO_UMG_API AHowTo_UMGGameModeBase : public AGameModeBase
- {
- GENERATED_BODY()
- public:
- /** 移除当前菜单控件,并在指定类(如有)中新建控件。*/
- UFUNCTION(BlueprintCallable, Category = "UMG Game")
- void ChangeMenuWidget(TSubclassOf
NewWidgetClass) ; -
- protected:
- /** 游戏开始时调用。*/
- virtual void BeginPlay() override;
-
- /** 游戏开始时,用作菜单的控件类。*/
- UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "UMG Game")
- TSubclassOf
StartingWidgetClass; -
- /** 用作菜单的控件实例。*/
- UPROPERTY()
- UUserWidget* CurrentWidget;
- };
3.在源文件中定义
- #include "HowTo_UMGGameModeBase.h"
-
- void AHowTo_UMGGameModeBase::BeginPlay()
- {
- Super::BeginPlay();
- ChangeMenuWidget(StartingWidgetClass);
- }
-
- void AHowTo_UMGGameModeBase::ChangeMenuWidget(TSubclassOf
NewWidgetClass) - {
- if (CurrentWidget != nullptr)
- {
- //将控件放到屏幕上
- CurrentWidget->RemoveFromViewport();
- CurrentWidget = nullptr;
- }
- if (NewWidgetClass != nullptr)
- {
- //创建控件
- CurrentWidget = CreateWidget
(GetWorld(), NewWidgetClass); - if (CurrentWidget != nullptr)
- {
- //放到屏幕上
- CurrentWidget->AddToViewport();
- }
- }
- }
4.创建玩家控制器类HowTo_UMGPlayerController
头文件
- #include "CoreMinimal.h"
- #include "GameFramework/PlayerController.h"
- #include "HowTo_UMGPlayerController.generated.h"
-
- /**
- *
- */
- UCLASS()
- class HOWTO_UMG_API AHowTo_UMGPlayerController : public APlayerController
- {
- GENERATED_BODY()
-
- public:
- virtual void BeginPlay() override;
-
- };
源文件
- #include "HowTo_UMGPlayerController.h"
-
- void AHowTo_UMGPlayerController::BeginPlay()
- {
- Super::BeginPlay();
- SetInputMode(FInputModeGameAndUI());
- }
===========================
创建ui蓝图MainMenu,加两个按钮

并分别创建点击事件

===========================
配置游戏
1.创建游戏模式类的蓝图

2.创建 PlayerController 的蓝图 ,命名为MenuPlayerController

3.打开该MenuPlayerController蓝图,并设置显示光标
4.编辑MenuGameMode蓝图

5.打开场景设置,设置游戏模式蓝图

======================================
构建二级UI
1.创建ui蓝图,NewGameMenu

分别设置点击事件