I am continuing the Battery Collector tutorial. This is the 16th video. Click here for the first part and here for the previous one.
Enabling UMG
PowerToWin
In BatteryCollectorGameMode.h, I am declaring a protected property PowerToWin:
/** The power needed to win the game */ UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Power", Meta = (BlueprintProtected = "true")) float PowerToWin;
I am also modifying the DecayRate property to make it Blueprint protected too.
I need an accessor for the HUD, so I declare it:
/** Returns power needed to win - needed for the HUD */ UFUNCTION(BlueprintPure, Category = "Power") float GetPowerToWin() const;
Because, the PowerToWin value is based on Character initial power, I need to define it in the BeginPlay function instead of the constructor. So I have to declare an override BeginPlay function:
virtual void BeginPlay() override;
In BatteryCollectorGameMode.cpp, I am defining my BeginPlay function:
void ABatteryCollectorGameMode::BeginPlay() { Super::BeginPlay(); // set the score to beat ABatteryCollectorCharacter* MyCharacter = Cast(UGameplayStatics::GetPlayerPawn(this, 0)); if (MyCharacter) { PowerToWin = (MyCharacter->GetInitialPower())*1.25f; } }
I am defining the GetPowerToWin function:
float ABatteryCollectorGameMode::GetPowerToWin() const { return PowerToWin; }
UMG in C++
In order to use UMG with C++, I need to modify some settings. I am modifying the file BatteryCollector.build.cs and add “UMG” to the list of public modules. I am also adding “Slate” and “SlateCore” to the list of private modules:
public class BatteryCollector : ModuleRules { public BatteryCollector(TargetInfo Target) { PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "UMG" }); PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" }); } }
In BatteryCollector.h, I am changing the include EngineMinimal.h by Engine.h
I need to regenerate my project files by right clicking on my BatteeryCollector.uproject file:
Hud
In BatteryCollectorMode.h, I am declaring a property to define the HUD class and the CurrentWidget:
/** The widget class to use for our HUD screen */ UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Power", Meta = (BlueprintProtected = "true")) TSubclassOf HUDWidgetClass; /** The instance of the HUD */ UPROPERTY() class UUserWidget* CurrentWidget;
In BatteryCollectorGameMode.cpp, I am including UserWidget.h:
#include "Blueprint/UserWidget.h"
It is important to have generated the Visual Studio project files to be able to include this file.
I am continuing the BeginPlay function to display the HUD:
if (HUDWidgetClass != nullptr) { CurrentWidget = CreateWidget(GetWorld(), HUDWidgetClass); if (CurrentWidget != nullptr) { CurrentWidget->AddToViewport(); } }
Next Step
Next, I will create the HUD blueprint
Leave a Reply