C++ Implementation for key handling

I wanted to avoid using Blueprints at all so looked into how to do this using C++.
I’m not sure if this is the optimal solution. Maybe there’s better one for C++.
But in any case it works just fine:

  1. Create a new C++ class based on APlayerController.
  2. Implement Tick and use the WasInputKeyJustPressed method there.

Since this is called each frame I added a IsMenuOpen flag to prevent running this multiple times. The flag is reset when the menu is closed (not shown here).

1 Like

This seems to be fine. The keypress is hard-coded however rather than using a project settings action mapping - it means a recompile to change it.
You should be aware that Blueprints are not something to be avoided - for simple tasks like menu interaction, blueprint is perfect. It’s perfectly performant for these tasks.

Normally, if I were implementing a menu I’d not use C++ at all. The second reason being it enables designers to adjust functionality slightly not relying on developers to change the C++ and rebuild the project. On a small project it is not an issue but large scale projects with many developers, Artists and map editors etc, this can be critical.

You are right, there’s nothing wrong with using Blueprints in principle. I just wanted to challenge myself to avoid it wherever possible.

For anyone who’s interested, I did find a better solution using InputComponent (which the PlayerController already has) and this way the Key can also be freely mapped in the project settings under Engine → Input without needing recompilation:

The code now looks like this:

void APuzzlePlatformsPlayerController::BeginPlay()
{
	Super::BeginPlay();

	if (InputComponent)
	{
		InputComponent->BindAction(
			"InGameMenu",
			IE_Released,
			this,
			&APuzzlePlatformsPlayerController::OpenInGameMenu
		);
	}
}

void APuzzlePlatformsPlayerController::OpenInGameMenu()
{
	if (IsMenuOpen) return;
	
	IsMenuOpen = true;

	UPuzzlePlatformsGameInstance* GameInstance = Cast<UPuzzlePlatformsGameInstance, UGameInstance>(GetGameInstance());

	if (GameInstance)
	{
		GameInstance->LoadInGameMenu();
	}
}
1 Like

Thanks for sharing. This is indeed a better solution.

Privacy & Terms