I am having some quite weird issues with UPROPERTY and I really couldn’t figure it out.
So right now I have a boolean value. In my base class constructor, I set the value to true. But for my derived class, I wanna override some behavior so I set it to false in its constructor. The problem is, as long as I marked the boolean value with UPROPERTY specifier, the value itself somehow got reset back to true.
I tried breakpoints and wrapped my bool in a setter to better trace it. I noticed the setter will only ran once, despite called twice (once in base constructor, once in the derived constructor). And even though the debugger tells me the value is indeed set to false in the constructor, it got reset to true somewhere before BeginPlay. Logging shows that both constructors indeed were executed and in correct order (first base then derived).
And if I removed the UPROPERTY specifier, it’s all normal. The breakpoint in the setter function will even trigger four times but idk.
I can’t for the life of me figuring out what’s happening here. Can someone provides some insight on this one? Thanks for any help you can offer!
Idk why it happens, but what I would try is to initialize the bool value only in the header, not the base class constructor, and then override it in the constructor of the child class to false.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "ParentA.generated.h"
UCLASS()
class YOUR_API AParentA : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AParentA();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
UPROPERTY(BlueprintReadWrite, EditAnywhere)
bool bMyBool = true;
};
.cpp
#include "ParentA.h"
AParentA::AParentA()
{
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void AParentA::BeginPlay()
{
Super::BeginPlay();
if (GEngine) {
if (bMyBool == true) {
GEngine->AddOnScreenDebugMessage(-1, 1, FColor::Cyan, GetName() + " My Bool is true");
}
else {
GEngine->AddOnScreenDebugMessage(-1, 1, FColor::Cyan, GetName() + " My Bool is false");
}
}
}
void AParentA::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
Derived
.h
#pragma once
#include "CoreMinimal.h"
#include "ParentA.h"
#include "ChildA.generated.h"
UCLASS()
class YOUR_API AChildA : public AParentA
{
GENERATED_BODY()
AChildA();
};