Unreal Crashes When Player Touches NPC

So I’m doing a test program with the C++ use of Unreal 4 where I have a character that moves with the directional keys and I have an NPC character. I want to make it so when the player reaches the NPC’s collision capsule, it shows a message saying “Hi, I’m Owen”. But once the player does that, Unreal crashes and I’m exited out. I think it has to do with the NPC code I came up with, but I just don’t see the issue. Could someone please help?

Crash Report

NPC.h

#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "Components/SphereComponent.h"
#include "Engine/Canvas.h"
#include "Engine/Font.h"
#include "Engine/World.h"
#include "NPC.generated.h"



UCLASS()
class GOLDEGG_API ANPC : public ACharacter
{
GENERATED_BODY()


public:
// Sets default values for this character's properties
ANPC(const FObjectInitializer& ObjectInitializer);
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = NPCMessage)
    FString NpcMessage;

UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Collision)
    USphereComponent* ProxSphere;

UFUNCTION(BlueprintNativeEvent, Category = "Collision")
    void Prox(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, 
UPrimitiveComponent* OtherComp,
        int32 OtherBodyIndex, bool bFromSweep, const FHitResult& 
SweepResult);

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = NPCMessage)
    FString name;

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = NPCMessage)
    UTexture2D* Face;

protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;

public:
// Called every frame
virtual void Tick(float DeltaTime) override;

// Called to bind functionality to input
virtual void SetupPlayerInputComponent(class UInputComponent* 
PlayerInputComponent) override;
};

NPC.cpp

#include "NPC.h"
#include "Engine/Canvas.h"
#include "Engine/Font.h"
#include "MyHUD.h"
#include "Avatar.h"



// Sets default values
ANPC::ANPC(const FObjectInitializer& ObjectInitializer) : 
Super(ObjectInitializer)
{
// Set this character to call Tick() every frame.  You can turn this off to 
improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
ProxSphere = ObjectInitializer.CreateDefaultSubobject<USphereComponent> 
(this, TEXT("Proximity Sphere"));
ProxSphere->AttachToComponent(RootComponent, 
FAttachmentTransformRules::KeepWorldTransform);
ProxSphere->SetSphereRadius(150.0f);
ProxSphere->OnComponentBeginOverlap.AddDynamic(this, &ANPC::Prox);
NpcMessage = "Hi, I'm Owen";

}

// Called when the game starts or when spawned
void ANPC::BeginPlay()
{
Super::BeginPlay();

}

 // Called every frame
void ANPC::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);

}
// Called to bind functionality to input
void ANPC::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);

}

void ANPC::Prox_Implementation(UPrimitiveComponent* OverlappedComponent, 
AActor* OtherActor, UPrimitiveComponent* OtherComp,
int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
if (Cast<AAvatar>(OtherActor) == nullptr)
{
    return;
}
APlayerController* PController = GetWorld()->GetFirstPlayerController();
if (PController)
{
    AMyHUD * hud = Cast<AMyHUD>(PController->GetHUD());
    hud->addMessage(Message(NpcMessage, 5.0f, FColor::White));
    //name + FString(":") + message
}
}

MyHUD.h

#include "Engine/World.h"
#include "Engine/Canvas.h"
#include "CoreMinimal.h"
#include "GameFramework/HUD.h"
#include "MyHUD.generated.h"

/**
 * 
 */
struct Message
	{
		FString message;
		float time = 5.f;
		FColor color = FColor::White;
		UTexture2D* tex;
		Message(FString iMessage, float iTime, FColor iColor)
		{
			message = iMessage;
			time = iTime;
			color = iColor;
		}
};
UCLASS()

class GOLDEGG_API AMyHUD : public AHUD
{
	GENERATED_BODY()
public:
	void addMessage(Message mg);


protected:

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = HUDFont) UFont* hudFont;
	TArray<Message>messages;
	virtual void DrawHUD() override;
	
};

MyHUD.cpp

#include "MyHUD.h"
#include "Engine/Canvas.h"
#include "Engine/Font.h"
#include "Kismet/GameplayStatics.h"
#include "Avatar.h"


void AMyHUD::DrawHUD()
{
	DrawHUD();
	for (int c = messages.Num() - 1; c >= 0; c--)
	{
		float outputWidth, outputHeight, pad = 10.f;
		GetTextSize(messages[c].message, outputWidth, outputHeight, hudFont, 1.f);

		float messageH = outputHeight + 2.f*pad;
		float x = 0.f, y = c * messageH;

		DrawRect(FLinearColor::Black, x, y, Canvas->SizeX, messageH);
		DrawText(messages[c].message, messages[c].color, x + pad, y + pad, hudFont);
		messages[c].time -= GetWorld()->GetDeltaSeconds();

		if (messages[c].time < 0)
		{
			messages.RemoveAt(c);
		}
	}
	
	DrawLine(200, 300, 400, 500, FLinearColor::Blue);
	DrawText("Greetings from Unreal!", FColor::White, 50, 50, hudFont);
}



void AMyHUD::addMessage(Message msg)
	{
		messages.Add(msg);
	}

I just added MyHUd.h and .cpp

leave VS open while I close UE?

It looks like a call to a function/property of an object that is a nullptr. It would help if you showed the code of myhud.cpp, too. Something goes sideways on line 39 in that file. Could it be that you have an undefined variable there?

Nothing jumps out. Did you make (significant) changes your header files while UE editor was open? There are some issues with the hot reload at times, that might cause such problems. I would try closing UE Editor, and do a Clean and Rebuild of code in Visual Studio, then relaunch UE Editor and see if the problem persists.

You can leave VS open. When you do the Rebuild, you should see in the Output pane something like:
Deleting old hot reload file: [path to file on your disk]-4974.dll

The number will be different.

I noticed this in my rebuild output window. Something about my dll file being denied. Not sure what that means.

I rebuilt and it deleted the files. Do I open UE after that from file explorer? Do I close VS first? When I open UE I get this

That’s odd. It can mean that there is a process running on your computer that is ‘locking’ the files, usually by using them.
I would first try to just do Rebuild again. Sometimes it helps :slight_smile:
If that doesn’t work, can you navigate to that folder, in File Explorer for example, and delete those files manually?

It all looks fine now. Can you still reproduce the issue with overlapping?

Here’s what my compile in UE looks like

Its still crashes. What’s the yellow line “Couldn’t Access Visual Studio”?

It didn’t crash, but I did get this output

It must mean the NPC thinks the player is a null pointer?
Can you think of what I’m missing that makes it think that?

Not sure about that yellow line, but it’s a warring that most likely has nothing to do with the crash.

It seems as if the code that you’re showing here is not the same as the one UE is running. At least the numbers do not coincide.

Can you add a line in the NPC.cpp file in Prox_Implementation function:

if (!ensure(hud != nullptr)) return;

in between these two lines:

AMyHUD * hud = Cast(PController->GetHUD());
if (!ensure(hud != nullptr)) return;
hud->addMessage(Message(NpcMessage, 5.0f, FColor::White));

and then compile and see if the crash is still happening.

No problem. I’ll convert my comment into an answer so that you can accept it, and this thread can be marked as solved.

I think that your problem is that the hud variable is returned as nulptr in this line:

AMyHUD * hud = Cast<AMyHUD>(PController->GetHUD());

Either the PlayerController you’re asking for the HUD has no HUD associated with it, or the Cast method fails, since the HUD the PlayerController is returning isn’t of the expeted type (AMyHUD).

I haven’t worked much with HUD in UE4, but I would suggest you add this line above the Cast call:

PController->ClientSetHUD(AMyHUD::StaticClass());
AMyHUD * hud = Cast<AMyHUD>(PController->GetHUD());

This will make the code work and your game will use your HUD class.

Also, to avoid an infinite loop, you have to add Super:: before DrawHUD() in your DrawHud method, as seen below.

 void AMyHUD::DrawHUD()
 {
	Super::DrawHUD();

Super means that it will first execute the parent class method. It is generally good practice to do so.

A note: a better place to set your HUD class as the game’s HUD would be in the constructor of your GameMode. You can see how it is done if you create a new, temporary, project and you select the C++ First Person template. I would look something like:

AGoldEggGameMode::AGoldEggGameMode()
{
	// set up all you need to ....
	
	
	// use our custom HUD class
	HUDClass = AMyHUD::StaticClass();
}

Ok. I had to change the HUD class in the pawn setting of game mode and change a line to look Super::DrawHud(). I appreciate the help and your time. Thanks.