Get Variable Stored In Player

I added a custom class to the PlayerCharacter in FPS1Character.h (I used the c++ FPS template). However I’m unable to get a reference to it. Same problem with variables.

  HpController HpController;

Player = UGameplayStatics::GetPlayerCharacter(GetWorld(), 0);
Player->... // I can't reference the HpController. I can't use FindComponentByClass<>() either because it is not a component, it's just a class.

The cause is probably because Player contains a pointer to an AActor instead of a pointer to FPS1Character. How do I solve this? I rather not add a HpController to the AActor class because 99% of all actors don’t need it.

What is HpController, and why does the member variable have the same name as the class type? Also, in order to access your character class’s member variable you need to cast to it. something like this Player = Cast < AFPS1Character > (UGameplayStatics::GetPlayerCharacter(GetWorld(), 0));

I simply named the member the same as the class-name. c++ always knows which is which and so do I. But perhaps this is bad coding?

HpController simply clamps the hitpoints between a min and max value and such.

Anyway yes the cast was the solution.

Ha Napoleon,

Two possibilities spring to mind:

First, like Chris528 said, this sounds like a situation for casting. The normal way to do this would be something like this:

Player = UGameplayStatics::GetPlayerCharacter(GetWorld(), 0);
AFPS1Character * fpsPlayer = Cast<AFPS1Character>(Player);
if (fpsPlayer == nullptr)
    // The player character isn't actually a FPS1Character
    // Otherwise, access the HpController using the fpsPlayer

If this doesn’t work, (or the cast returns null), you might look at the second piece: You may want to select the default player character class. In a C++ game mode, you can use the constructor and set the DefaultPlayerCharacterClass to the class you want like this:

DefaultPawnClass = AFPS1Character::StaticClass();

In a Blueprint game mode, you can edit the Blueprint by selecting the character class in the Default Pawn Class option under the Classes section.

If neither of those help, I’ve probably misunderstood your question.

In either case, please let me know if this helps, and I’ll try to help more as needed.


First possibility worked. Thanks. Note that (obviously) I also had to add:

#include "FPS1Character.h"

to make it work.