Leave Server handy implementation

In the previous part before steam and stuff. I wrote this handy chunk of code.

This is used as a wrapper for LoadMainMenu(). It checks for host and then kicks all clients back to main menu before making the host leave. It seems to work just fine for me. Now i just call it in OnNetworkFailure too.

I would like some help with the check for host though, do not know if this is the right implementation?

void UPuzzlePlatformsGameInstance::LeaveServer()
{
	if (!ensure(GEngine != nullptr)) return;

	GEngine->AddOnScreenDebugMessage(0, 10.f, FColor::Green, FString::Printf(TEXT("Leaving...")));
	UE_LOG(LogTemp, Warning, TEXT("Left Server Run"));

	APlayerController* PlayerController = GetFirstLocalPlayerController();
	if (!ensure(PlayerController != nullptr)) return;

	const UWorld* World = GetWorld();
	if (!ensure(World != nullptr)) return;

	if (World->IsNetMode(World->GetNetMode())) 
	{
		GEngine->AddOnScreenDebugMessage(0, 10.f, FColor::Green, FString::Printf(TEXT(" Host Left Server...")));
		
		TArray<AActor*> FoundControllers;
		UGameplayStatics::GetAllActorsOfClass(GetWorld(), APlayerController::StaticClass(), FoundControllers);

		for (AActor* Actor : FoundControllers)
		{
			APlayerController* Controller = Cast<APlayerController>(Actor);
			if (Controller != nullptr && Controller != PlayerController) {
				Controller->ClientTravel("/Game/MenuSystem/MainMenu?listen", ETravelType::TRAVEL_Absolute);
			}
		}
	}

	PlayerController->ClientTravel("/Game/MenuSystem/MainMenu?listen", ETravelType::TRAVEL_Absolute);
}

Now that network failure does the job anyways i updated my code to:

void UPuzzlePlatformsGameInstance::OnNetworkFailure(UWorld* World, UNetDriver* NetDriver, ENetworkFailure::Type FailureType, const FString& ErrorString)
{
	GEngine->AddOnScreenDebugMessage(0, 10.f, FColor::Red, FString::Printf(TEXT("Host Left Server...")));
	LeaveServer();
}

and this:

void UPuzzlePlatformsGameInstance::LeaveServer()
{
	if (!ensure(GEngine != nullptr)) return;

	GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Green, FString::Printf(TEXT("Leaving...")));
	UE_LOG(LogTemp, Warning, TEXT("Left Server Run"));

	APlayerController* PlayerController = GetFirstLocalPlayerController();
	if (!ensure(PlayerController != nullptr)) return;

	PlayerController->ClientTravel("/Game/MenuSystem/MainMenu?listen", ETravelType::TRAVEL_Absolute);
}

This means that if the host leaves it shows an error. If the client leaves there is no error

1 Like

Privacy & Terms