GetDefaultSubobjectByName returns nullptr

I am trying to use OnComponentHit function and AddDynamic, by casting the box collision I made in a different class into a pointer. But it always return a nullptr.

Super::BeginPlay();
	Player = Cast<APlayerCharacter>(UGameplayStatics::GetActorOfClass(this, PlayerClass));
	Box = Cast<UBoxComponent>(Player->GetDefaultSubobjectByName("DamageBox"));
	/*if (Box == nullptr) return;*/
	Box->OnComponentHit.AddDynamic(this, &AItem::OnHit);

The collision box is in my player character cpp class and I am trying yo use the OnHit function from my Item class to deal damage. And whenever I hit play, it will crash the editor.

Thx!

1 Like