Why is my game crashing when adding a delegate in beginplay?

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 :frowning:

// 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);
       }
    }
}

Hey,
Welcome to the forums!

Could you attach a crash log?

Some things to make you should be aware of:

  • Your OnSphereOverlap method must be a UFUNCTION().
  • After creating your OnSphereOverlap method you should always compile from the IDE with the editor closed.
    You might have accidentally compiled using Live Coding which can cause issues like that.

Sorry for the late answer! I actaully fixed it by renaming my Sphere variable. I had earlier made a Sphere Component with the same name, so it now works by changing my Sphere variable name to Sphere2.

So yeah, I believe this was a mistake of me using live coding instead of recompiling the project.