I’m in the camp that believes in being clear about what the code communicates: if it’s supposed to fail, it should fail.
Hence, I went forward with a piece of code that simply quits the play session if a null pointer is detected. It even logs out the function and line number where it’s detected. Currently, it only works in a context which can provide a reference to a valid UWorld*
pointer - so in AActor
and UActorComponent
classes for now.
// Put this in a .h file somewhere.
#include "Kismet/KismetSystemLibrary.h"
#define GUARD(ptr, world) \
if ((ptr) == nullptr)\
{\
UE_LOG(LogTemp, Error, TEXT("nullptr at %s: %d"), TEXT(__FUNCTION__), __LINE__);\
UKismetSystemLibrary::QuitGame((world), (world)->GetFirstPlayerController(), EQuitPreference::Quit, false);\
}
Inside an UActorComponent
's BeginPlay
function, use it like:
// Called when the game starts
void UDoorOpener::BeginPlay()
{
Super::BeginPlay();
GUARD(Trigger, GetWorld());
GUARD(DoorOpenInstigator, GetWorld());
...
}
Be careful since GetWorld()
returns nullptr
in the constructor! Use it only when you know for sure that a valid UWorld*
pointer is available in that context - according to its definition, it will also be nullptr
if a UActorComponent
is not spawned in a level!
This of course won’t prevent crashes if there’s anything else that may break the game in a later piece of code.