I already figured it out and the following question arose.
In a new C++ project I created the character Cube. The cube has two public variables.
Cube.cpp
// Sets default values
ACube::ACube()
{
// Set this pawn to call Tick() every frame. You can turn this off to improve performance if you dont need it.
PrimaryActorTick.bCanEverTick = true;
static ConstructorHelpers::FObjectFinder<UStaticMesh>C(TEXT("StaticMesh'/Game/StarterContent/Shapes/Shape_Cube.Shape_Cube'"));
UStaticMeshComponent* Cube = CreateDefaultSubobject<UStaticMeshComponent>("Cube");
Cube->SetupAttachment(RootComponent);
Cube->SetStaticMesh(C.Object);
MaxHealth = 200.f;
}
// Called every frame
void ACube::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
Health = rand() % 100 + 50.f;
}
I also created a C++ class Widget consisting of one health bar.
HealthBar.h
#pragma once
#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "HealthBar.generated.h"
UCLASS()
class CUBEHEALTH_API UHealthBar : public UUserWidget
{
GENERATED_BODY()
protected:
UPROPERTY(BlueprintReadWrite, meta = (BindWidget))
class UProgressBar* Bar;
};
I got the following result.
I need the health bar to correspond to the value of the Health variable, which is constantly changing. How to do this in C++?