I got a nullptr error in Unreal Engine 4. I tried to attach HealthComponent but I failed.
Exception: read access violation. this->HealthComponent was nullptr.
What should I do to fix it?
STUBaseCharacter.h
#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "STUBaseCharacter.generated.h"
class UCameraComponent;
class USTUHealthComponent;
class USpringArmComponent;
class UTextRenderComponent;
UCLASS()
class SHOOTTHEMUP_API ASTUBaseCharacter : public ACharacter
{
GENERATED_BODY()
public:
ASTUBaseCharacter(const FObjectInitializer &ObjInit);
protected:
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Components")
USTUHealthComponent *HealthComponent;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Components")
USpringArmComponent *SpringArmComponent;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Components")
UCameraComponent *CameraComponent;
STUBaseCharacter.cpp
#include "Player/STUBaseCharacter.h"
#include "Camera/CameraComponent.h"
#include "Components/InputComponent.h"
#include "Components/STUCharacterMovementComponent.h"
#include "Components/STUHealthComponent.h"
#include "Components/TextRenderComponent.h"
#include "GameFramework/Controller.h"
#include "GameFramework/SpringArmComponent.h"
DEFINE_LOG_CATEGORY_STATIC(LogBaseCharacter, All, All);
ASTUBaseCharacter::ASTUBaseCharacter(const FObjectInitializer &ObjInit)
: Super(
ObjInit.SetDefaultSubobjectClass<USTUCharacterMovementComponent>(ACharacter::CharacterMovementComponentName))
{
PrimaryActorTick.bCanEverTick = true;
SpringArmComponent = CreateDefaultSubobject<USpringArmComponent>("SpringArmComponent");
SpringArmComponent->SetupAttachment(GetRootComponent());
SpringArmComponent->bUsePawnControlRotation = true;
CameraComponent = CreateDefaultSubobject<UCameraComponent>("CameraComponent");
CameraComponent->SetupAttachment(SpringArmComponent);
HealthComponent = CreateDefaultSubobject<USTUHealthComponent>("HealthComponent");
HealthTextComponent = CreateDefaultSubobject<UTextRenderComponent>("HealthTextComponent");
HealthTextComponent->SetupAttachment(GetRootComponent());
}
void ASTUBaseCharacter::BeginPlay()
{
Super::BeginPlay();
check(HealthComponent); // error
check(HealthTextComponent);
check(GetCharacterMovement());
OnHealthChanged(HealthComponent->GetHealth());
HealthComponent->OnDeath.AddUObject(this, &ASTUBaseCharacter::OnDeath);
HealthComponent->OnHealthChanged.AddUObject(this, &ASTUBaseCharacter::OnHealthChanged);
LandedDelegate.AddDynamic(this, &ASTUBaseCharacter::OnGroundLanded);
}
What is the problem here? If I delete these fields the project is working.
check(HealthComponent);
OnHealthChanged(HealthComponent->GetHealth());
HealthComponent->OnDeath.AddUObject(this, &ASTUBaseCharacter::OnDeath);
HealthComponent->OnHealthChanged.AddUObject(this, &ASTUBaseCharacter::OnHealthChanged);
Also if I open BP_Character and I choose HealthComponent field there is nothing in the details place