Cast from my Character to UActorComponent.

I want to access GetHealth() from my character, but I don’t know how to do it.

This is UHealthComponent;

UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class TESTINGC_API UHealthComponent : public UActorComponent
{
GENERATED_BODY()

public:
// Sets default values for this component’s properties
UHealthComponent();

float GetHealth() const;

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

UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = “Health”)
float DefaultHealth;

UPROPERTY(BlueprintReadOnly)
float Health;

UFUNCTION()
void TakeDamage(AActor* DamagedActor, float Damage, const class UDamageType* DamageType, class AController* InstigatedBy, AActor* DamageCauser);
};

I’ve tried con Cast, but it doesn’t work. Can anybody help me?

UHealthComponent * HealthComp = Character->FindComponentByClass<UHealthComponent>();

Hi, thank you very much for your answer, but it still doesn’t work.

I’ve put this inside my class ATestingCCharacter in BeginPlay():

class ATestingCCharacter* Character;

UHealthComponent* Health = Character->FindComponentByClass< UHealthComponent>();

But the following error comes out:

C4700 uninitialized local variable ‘Character’ used.

I think I’m confused…

Well yes, you just said to the computer that “Character” is a pointer to an ATestingCCharacter object, but right now, it isn’t pointing to anything since you didn’t put “Character = something” anywhere. If this code is inside your character class, then you can just leave the Character part out.



void ATestingCCharacter::BeginPlay()
{
     Super::BeginPlay();

     UHealthComponent* HealthComp = FindComponentByClass<UHealthComponent>();
     if (HealthComp)
     {
        // Found the health component. You can now access it safely.
        // You can get the current health like this HealthComp->GetHealth();
     }
}


I wrote the code, but it doesn’t work. It doesn’t do anything and it doesn’t generate errors. I’ve tried many thing and nothing. What could it be?