Announcement

Collapse
No announcement yet.

HUD causes game to Crash, if spawning 2 players

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    HUD causes game to Crash, if spawning 2 players

    Hi,

    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
    Code:
            //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
    Code:
            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.

    #2
    Hello.

    DrawHUD might be ticking when owning pawn is not AStdCharacter actually, check it against null before accessing it.
    Alone: The Untold - a story driven horror game

    Comment


      #3
      Thank you, that worked!
      Code:
              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);
      	}

      Comment


        #4
        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.
        Sr. Engine Programmer @ www.playspace.com - moritzwundke.com
        Remember: be polite and respect other peoples opinions - Join the Unofficial Unreal Discord Channel - Found a bug? Then use the Bug Report Form to get it fixed ^^

        Comment

        Working...
        X