Custom USceneComponent initialization return nullptr

When i initialize my custom USceneComponent, it runs into EXCEPTION_ACCESS_VIOLATION error, caused by component pointer being nullptr.

DynamicCameraComponent.h

UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class LOR2_API UDynamicCameraComponent : public USceneComponent
{
	GENERATED_BODY()

	UPROPERTY(EditAnywhere)
		USpringArmComponent* m_arm;
	UPROPERTY(EditAnywhere)
		UCameraComponent* m_camera;
public:	
	UDynamicCameraComponent();
}

DynamicCameraComponent.cpp

UDynamicCameraComponent::UDynamicCameraComponent()
	: Super()
{
	m_arm = CreateDefaultSubobject<USpringArmComponent>(TEXT("Arm"));
	m_arm->TargetArmLength = 85;
	m_arm->SetupAttachment(this);

	m_camera = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera"));
	m_camera->FieldOfView = 75;
	m_camera->SetupAttachment(m_arm);
}

Im initializing component using standard method from UE4 Reference Guide:

	m_dyna_camera = CreateDefaultSubobject<UDynamicCameraComponent>(TEXT("Dynamic Camera"));
	m_dyna_camera->Init(100, 75); //My custom function
	m_dyna_camera->SetupAttachment(RootComponent);

But when i try to get the component, it runs into exception with nullptr:

AddMovementInput(m_dyna_camera->GetCamera()->GetForwardVector(), axis * m_props.movementSpeed); // EXCEPTION_ACCESS_VIOLATION m_dyna_camera is nullptr reference

So what is right way to initialize component?

Edit: I figured out, that m_dyna_camera variable gets damaged only when i press “Play” button. Before, at engine startup or levels loading, it initializing right, but gets damaged when i start playing.

Edit 2: I noticed, that in blueprint editor, my inherited component’s default value equals None

Edit 3: After some experiments i figured out, that it’s problem with initalizing children, so what is right way to do it?

1 Like

Resolved:
I was initializing component children giving them the SceneComponent as container, but you can’t just initialize USceneComponent not in AActor.

m_arm = Oinit.CreateDefaultSubobject<USpringArmComponent>(this, TEXT("Arm")); //this "this" MUST BE AActor, it's a container for Component

So just initialize all the components in AActor and then attach them to USceneComponent