Download

Replicated spawned actor reference null

Hi! I’m trying to spawn a replicated actor through a Server UFUNCTION. I can change its properties inside the function that actually spawns it, but when I try to do anything outside it I get a null reference.

Here’s my code:

Survivor.h


    UPROPERTY(BlueprintReadOnly, EditAnywhere, Category = "References", Replicated)
        class AWeapon* CurrentWeapon;



        UFUNCTION(WithValidation, Server, Reliable, BlueprintCallable)
        void FInput(TSubclassOf<AWeapon> WeaponToSpawn);


Survivor.cpp



bool ASurvivor::FInput_Validate(TSubclassOf<AWeapon> WeaponToSpawn)
{
    return true;
}

void ASurvivor::FInput_Implementation(TSubclassOf<AWeapon> WeaponToSpawn)
{
    if (CurrentWeapon == nullptr && HasAuthority())
    {
        FAttachmentTransformRules TransformRules = FAttachmentTransformRules(EAttachmentRule::KeepRelative, EAttachmentRule::KeepRelative, EAttachmentRule::KeepRelative, true);
        CurrentWeapon = GetWorld()->SpawnActor<AWeapon>(WeaponToSpawn);
        CurrentWeapon->AttachToComponent(GetMesh(), TransformRules, FName(TEXT("weapon_AK47")));
        D("finput sent");
    }
}


This works fine. The problem is when I try to acess the CurrentWeapon after it has spawned.

Survivor Blueprint:
SurvivorBP.png

After the weapon is attached and I try to shoot:

Not sure why, this only happens outside the FInput function.

Hope someone can help! Thanks.

It seems like the problem is that the actor assigned to CurrentWeapon is not set to be replicated (not just the UPROPERTY but an actual boolean in the actor). And / or that it is not relevant to the player at the time of the left mouse button press.

The Client has to be the Owner of both Survivor and the spawned Weapon otherwise it won’t be able to send the RPC to the server from them. Call SetOwner server-side and pass it either the client PlayerController or Pawn or something else that the Client already is Owner of.