Download

SetOwner() not working on begin play

So i have this piece of code i call on MyCharacter::BeginPlay()


FActorSpawnParameters SpawnParams;
    SpawnParams.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
    CurrentWeapon = GetWorld()->SpawnActor<AaFireWeapon>(StarterWeapon, FVector::ZeroVector, FRotator::ZeroRotator);
    if (CurrentWeapon)
    {
        //CurrentWeapon->WeaponOwner = this;
        CurrentWeapon->SetOwner(this);
        CurrentWeapon->AttachToComponent(GetMesh(), FAttachmentTransformRules::SnapToTargetNotIncludingScale, HandSocket);
    }

It spawns Debug weapon at begin play. But for some reason


    UE_LOG(LogTemp, Warning, TEXT("Weapon Owner Is %s"),
        *GetNameSafe(GetOwner()));
    WeaponOwner = Cast<AaPlayerPawnMaster>(GetOwner());

This piece of code in my WeaponClass on** BeginPlay **returns NULL. But if i put inside my Trace function. It works.

That’s because the actor has already begun play when you spawn it, and you can’t garauntee the order in which BeginPlay() will be called between actors anyway.

In this particular case you can use deferred actor spawn to set the owner.