I started a new project and copied in some of the blueprints from the Multiplayer Shootout example with the intention of converting it to C++. I did the C++ for the player controller first and when I replaced the blueprint with it there was a bug.
When I click a mouse button the cursor unlocks from the game window. I tried binding the mouse clicks to functions and they are not being called when I click. I assume I’ve done something wrong in setting up the HUD. Something to do with the input mode maybe, I can’t figure it out. Here is the code:
MyPlayerController.h:
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/PlayerController.h"
#include "Blueprint/UserWidget.h"
#include "MyPlayerController.generated.h"
/**
*
*/
UCLASS()
class FACTION_API AMyPlayerController : public APlayerController {
GENERATED_BODY()
public:
AMyPlayerController();
virtual void SetupInputComponent() override;
UFUNCTION(Client, Reliable, BlueprintCallable)
void ClientPostLogin();
UFUNCTION(BlueprintCallable)
void HideInGameMenu();
void SetupInGameUI();
void ShowInGameMenu();
void ToggleInGameMenu();
protected:
bool bIsInGameMenu = false;
public:
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "UI")
TSubclassOf<UUserWidget> HUDWidgetTemplate;
UPROPERTY()
UUserWidget* HUDWidgetInstance;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "UI")
TSubclassOf<UUserWidget> InGameMenuWidgetTemplate;
UPROPERTY()
UUserWidget* InGameMenuWidgetInstance;
};
MyPlayerController.cpp:
#include "MyPlayerController.h"
AMyPlayerController::AMyPlayerController() {
bShowMouseCursor = true;
}
void AMyPlayerController::SetupInputComponent() {
Super::SetupInputComponent();
InputComponent->BindAction("InGameMenu", IE_Pressed, this, &AMyPlayerController::ToggleInGameMenu);
}
void AMyPlayerController::ClientPostLogin_Implementation() {
SetupInGameUI();
}
void AMyPlayerController::SetupInGameUI() {
if (this->IsLocalPlayerController()) {
if (HUDWidgetTemplate) {
if (!HUDWidgetInstance) {
HUDWidgetInstance = CreateWidget(this, HUDWidgetTemplate);
}
if (!HUDWidgetInstance->GetIsVisible()) {
HUDWidgetInstance->AddToViewport();
}
}
if (InGameMenuWidgetTemplate) {
if (!InGameMenuWidgetInstance) {
InGameMenuWidgetInstance = CreateWidget(this, InGameMenuWidgetTemplate);
}
}
}
}
void AMyPlayerController::ShowInGameMenu() {
InGameMenuWidgetInstance->AddToViewport();
FInputModeUIOnly MenuMode;
MenuMode.SetWidgetToFocus(InGameMenuWidgetInstance->GetCachedWidget());
SetInputMode(MenuMode);
bIsInGameMenu = true;
}
void AMyPlayerController::HideInGameMenu() {
InGameMenuWidgetInstance->RemoveFromParent();
FInputModeGameOnly GameMode;
SetInputMode(GameMode);
bIsInGameMenu = false;
}
void AMyPlayerController::ToggleInGameMenu() {
if (bIsInGameMenu)
HideInGameMenu();
else
ShowInGameMenu();
}