Download

Shooter Game c++ doesn't result in an infinite loop?

I’ve been going through the shooter game example that epic provides that shows an example of a FPS based on C++. However the below code is stumping me.

How does an onrep call a function that sets that sets the variable that should trigger the onrep again, without resulting in an infinite loop. Recreating the below code in a blueprint does indeed cause an infinite loop.

Does c++ handle onrep differently than blueprints do?

ShooterCharacter.h



/** currently equipped weapon */
    UPROPERTY(Transient, ReplicatedUsing = OnRep_CurrentWeapon)
    class AShooterWeapon* CurrentWeapon;

/** updates current weapon */
void SetCurrentWeapon(class AShooterWeapon* NewWeapon, class AShooterWeapon* LastWeapon = NULL);

/** current weapon rep handler */
UFUNCTION()
void OnRep_CurrentWeapon(class AShooterWeapon* LastWeapon);


ShooterCharacter.cpp



void AShooterCharacter::**OnRep_CurrentWeapon**(AShooterWeapon* LastWeapon)
{
**SetCurrentWeapon**(CurrentWeapon, LastWeapon);
}

void AShooterCharacter::**SetCurrentWeapon**(AShooterWeapon* **NewWeapon**, AShooterWeapon* LastWeapon)
{
    AShooterWeapon* LocalLastWeapon = NULL;

    if (LastWeapon != NULL)
    {
        LocalLastWeapon = LastWeapon;
    }
    else if (NewWeapon != CurrentWeapon)
    {
        LocalLastWeapon = CurrentWeapon;
    }

    // unequip previous
    if (LocalLastWeapon)
    {
        LocalLastWeapon->OnUnEquip();
    }

**CurrentWeapon = NewWeapon**;

    // equip new one
    if (NewWeapon)
    {
        NewWeapon->SetOwningPawn(this);    // Make sure weapon's MyPawn is pointing back to us. During replication, we can't guarantee APawn::CurrentWeapon will rep after AWeapon::MyPawn!

        NewWeapon->OnEquip(LastWeapon);
    }
}


In C++, setting a replicated value to itself shouldn’t force another replication event. However, it should likely be wrapped in a check to prevent that.




// Only allow the server to touch this.
if (GetRole() >= ROLE_Authority)
{
   CurrentWeapon = NewWeapon;
}



So do blueprints treat OnRep differently then? For instance I wrote the same function in blueprints and got the infinite loop error. I updated it to put the assignment after an authority guard.
OnRepCurWeap.png

I’m not super skilled at writing c++, but I know enough to read it, and my intention is to port this over to blueprints.

RepNotify in Blueprints fire on Server and Clients.

In C++, OnRep is only fired on clients NOT server.

That is why your BP infinite loops and C++ doesnt.

So then does the onrep not get called in c++ if the variable is set by the client?

Correct, OnRep is only fired when its replicated from server to client.