Quit game by code

I have a slate UI with a button to quit the game.
I looked at the ShooterGame example where it is done like this:

void AMainMenuHUD::QuitClicked()
{
	UGameViewportClient* const Viewport = PlayerOwner->GetGameInstance()->GetGameViewportClient();
	if (Viewport)
	{
		Viewport->ConsoleCommand("quit");
	}
}

But compiling fails with the message

Error	1	error C2027: use of undefined type 'UGameInstance'

I see that PlayerOwner is actually of type ULocalPlayer in the ShooterExample, whereas mine is of type APlayerController.
The method GetGameInstance does exist there aswell.

I also read that using console commands should be avoided, is there any other method?

How do I quit the game from code?

Hello Ekhaede.

I think the reason it may be crashing is because you are trying to boot the Viewport from the game rather than the player

You could try using this:
GetWorld()->GetFirstPlayerController()->ConsoleCommand(“quit”);

Please let me know if this works

Thanks

1 Like

This worked, thank you.

This does not work on PS4 (4.8.2)

Also not working on PC 4.9.2 (with seprate window PIE)

I’ve used this method since 4.1 and it’s never worked on PIE. What do you expect to happen? Would you like the Editor to close down when using this in PIE?

I prefer FPlatformProcess::RequestExit(false);

I could not find that function, did you perhaps mean FGenericPlatformMisc::RequestExit(false); ?

APlayerController* SpecificPlayer = GetWorld()->GetFirstPlayerController();
UKismetSystemLibrary::QuitGame(GetWorld(), SpecificPlayer, EQuitPreference::Quit,true);

APlayerController* SpecificPlayer = GetWorld()->GetFirstPlayerController();
UKismetSystemLibrary::QuitGame(GetWorld(), SpecificPlayer, EQuitPreference::Quit,true);

you can use

UKismetSystemLibrary::QuitGame(GetWorld(),UGameplayStatics::GetPlayerController(GetWorld(),0),EQuitPreference::Type::Quit,false);

make sure to #include"Kismet/KismetSystemLibrary.h"
check out unreal docs : UKismetSystemLibrary::QuitGame

2 Likes