CreateDefaultSubObject fails to create an UStaticMeshComponent properly in constructor

Hey guys I’ve had the following problem for a few days now, so in short I’ve had problems creating a UStaticMeshComponent in the actor constructor. Currently at the time of writing the code successfully creates the PlayerCollider, but when trying to create the UStaticMeshComponent, it fails completely at creating it.

APlayerPawn header:

#include "CoreMinimal.h"
#include "GameFramework/Pawn.h"
#include "Camera/CameraComponent.h"
#include "Components/CapsuleComponent.h"
#include "Components/StaticMeshComponent.h"
#include "PlayerPawn.generated.h"

class UCameraComponent;

UCLASS()
class CHAOSPILKING_API APlayerPawn : public APawn
{
	GENERATED_BODY()

public:
	// Sets default values for this pawn's properties
	APlayerPawn();

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

public:	
	// Called every frame
	virtual void Tick(float DeltaTime) override;

	UPROPERTY()
	TObjectPtr<UCapsuleComponent> PlayerCollider;

	UPROPERTY()
	TObjectPtr<UStaticMeshComponent> PlayerMesh;

	UPROPERTY()
	TObjectPtr<UCameraComponent> PlayerCamera;
	
};

APlayerPawn cpp:

#include "Player/PlayerPawn.h"

// Sets default values
APlayerPawn::APlayerPawn()
{
 	// Set this pawn to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = false;

	PlayerCollider = CreateDefaultSubobject<UCapsuleComponent>(TEXT("PlayerCollider"));
	RootComponent = PlayerCollider;
	PlayerCollider->SetCollisionProfileName(TEXT("Pawn"));

	PlayerCollider->SetLineThickness(1.f);
	PlayerCollider->SetHiddenInGame(false);
	
	PlayerMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("PlayerMesh"));
	PlayerMesh->SetupAttachment(PlayerCollider);

	PlayerCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("PlayerCamera"));
	PlayerCamera->SetupAttachment(PlayerMesh);
}

PlayerPawn after creation:
kuva

I would be very greatful if someone would help me out of this pickle with some kind of fix and if I’m actually doing it wrong then at least point me to the “best practice” implementation.

Thanks in advance.

The only piece that stands out to me is your lack or UPROPERTY specifiers. Generally for BP editable components you will want

UPROPERTY(EditDefaultsOnly, BlueprintReadWrite)

It works for the RootComponent because it has the appropriate UPROPERTY specifiers (not yours but the location RootComponent is defined)

1 Like

That seemed to fix the problem, thanks.

The lack of UPROPERTY specifiers was because I’d like to code my game with little to no blueprints as to learn cpp, but apparently it still needs the UPROPERTY(EditDefaultsOnly) to work.

It kind of escaped my mind, since I’ve mostly seen them as “tags” for blueprint editing.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.