I am trying to add a OnComponentBeginOverlap delegate but it crashes when I do so in the BeginPlay() function. It does NOT crash if I add the delegate in the constructor though.
I have read that it’s best practice to add delegates in the BeginPlay to avoid issues, so I kinda want to fix this issue ![]()
// Sets default values
AItem::AItem()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
ItemMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("ItemMeshComponent"));
RootComponent = ItemMesh;
Sphere = CreateDefaultSubobject<USphereComponent>(TEXT("SphereComponent"));
Sphere->SetupAttachment(GetRootComponent());
}
// Called when the game starts or when spawned
void AItem::BeginPlay()
{
Super::BeginPlay();
Sphere->OnComponentBeginOverlap.AddDynamic(this, &AItem::OnSphereOverlap);
}
void AItem::OnSphereOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep,
const FHitResult& SweepResult)
{
if (OtherActor)
{
const FString Name = OtherActor->GetName();
if (GEngine)
{
GEngine->AddOnScreenDebugMessage(1, 30.f, FColor::Red, Name);
}
}
}