HUD causes game to Crash, if spawning 2 players


i’m new to program in C++, but not new in programming at all (C on micro-controllers for years).
But now i ran into a problem and i don’t understand the cause of this.

My code is mostly from the First Person Shooter C++ Tutorial. I only left out the First-Person Mesh and all Animation stuff.
I tried now to add a HUD. I set up a public variable for my AStdCharacter inside of AStdCharacter.h

        //Current Health of the Player
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Health)
	float fHealth;

I’m initializing it with 100.
Inside of the PlayerHUD.cpp, i added

        const float fLower = Canvas->ClipY * 0.95f;
	const float fLeft = Canvas->ClipX * 0.025f;
        AStdCharacter* MyPawn = Cast<AStdCharacter>(GetOwningPawn());
	float health = MyPawn->fHealth;
	DrawText(FString::Printf(TEXT("Health %f"), health),  FColor::Black, fLeft, fLower, HUDFont, 2.0f, false);

This worked for a time - then i tried to spawn 2 Players (Inside of the Editor, with “Play”). The game crashed (Access violation - code c0000005 (first/second chance not available))

As soon as i want to spawn a second player the game crashes. If i only spawn 1 Player, everything is fine. What am i doing wrong? I’m sure i missed something essential out, but i don’t know what.


DrawHUD might be ticking when owning pawn is not AStdCharacter actually, check it against null before accessing it.

Thank you, that worked!

        AStdCharacter* MyPawn = Cast<AStdCharacter>(GetOwningPawn());
	if (MyPawn)
		float health = MyPawn->fHealth;
		this->DrawText(FString::Printf(TEXT("Health %f"), health),  FColor::Black, fLeft, fLower, HUDFont, 2.0f, false);

Take into account that you are now using C++, any access to a NULL pointer will result in crashes. I recommend you to ALWAYS check that the pointer is not pointing to NULL.

If you are checking for an UObject (Garbage Collected) you can compare with NULL while you can use nullptr if its a base C++ pointer or a shared pointer. Take into account that you can not assign nullptr to anything, this is because for UObject you normally use NULL to invalidate. In both cases the if clause will just work fine.