Section 2, Lecture 40 : Leaving A Server - Client Game crashes when Server Host leaves to menu. - A quick fix

If the host of the server leaves to menu or quits the game, all connected game clients will crash.

To fix this we can simply add a new function to our game instance .h and .cpp file. Then bind it to a built in engine network function.
I’ll call it NetworkError, but you can call it anything you like. I’m using the game instance Init() function to bind the delegate.

side node: If you’re using your own game instance make sure you rename the UPuzzlePlatformInstance to your game instance!!!

In your game instance .h file add this to the public section.

public:
void NetworkError(UWorld* World, UNetDriver* NetDriver, ENetworkFailure::Type FailureType, const FString& ErrorString);

In the game instance .cpp file add this and simply call the LoadMainMenu function in this NetworkError function.

void UPuzzlePlatformInstance::NetworkError(UWorld* World, UNetDriver* NetDriver, ENetworkFailure::Type FailureType, const FString& ErrorString)
{
 LoadMainMenu();
}

Now in order for this to get called automatically, we need to bind this function to the engine’s OnNetworkFailure. I will bind it by calling this engine function in the Init function.

void UPuzzlePlatformInstance::Init()
{
 UE_LOG(LogTemp, Warning, TEXT("Found class %s"), *MenuClass->GetName());

 UEngine* Engine = GetEngine();
 if (!ensure(Engine != nullptr)) return;
 Engine->OnNetworkFailure().AddUObject(this, &UPuzzlePlatformInstance::NetworkError);
}

That’s it! Now if you launch two games and as the server quit game or quit to menu, all clients will simply go to the main menu instead of crashing.

6 Likes

Awesome work!

1 Like

Privacy & Terms