Hi everyone…
I am facing a problem with replication. I am spawning weapons from the character class on the server. The spawning works perfectly on the server but on the client, the weapons appear the be attached to the server in some way and move when the server moves but I am not entirely sure what is happening.
Codes
Character.h
protected:
/* [Server] */
void SpawnDefaultWeapon();
Character.cpp
void APSETPCCharacter::BeginPlay()
{
if (Role == ROLE_Authority)
{
SpawnDefaultWeapon();
}
}
void APSETPCCharacter::SpawnDefaultWeapon()
{
if (Role < ROLE_Authority)
{
return;
}
if (DefaultWeapon)
{
UWorld* World = GetWorld();
if (World)
{
ABaseWeapon* TempWeapon = GetWorld()->SpawnActor<ABaseWeapon>(DefaultWeapon);
TempWeapon->SetOwner(this);
TempWeapon->OnEquip();
CurrentWeapon = TempWeapon;
}
}
}
void APSETPCCharacter::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME(APSETPCCharacter, CurrentWeapon);
}
Weapon.h
UPROPERTY(Category = WeaponMesh, VisibleAnywhere, BlueprintReadOnly)
class UStaticMeshComponent* ItemMesh;
void SetOwner(APSETPCCharacter* NewOwningPawn);
/** Pawn which owns this weapon */
UPROPERTY(Replicated)
APSETPCCharacter* OwningPawn;
/** Called when the weapon is equiped */
void OnEquip();
/** What to do when the weapon is spawned */
void OnWeaponSpawn();
Weapon.cpp
ABaseWeapon::ABaseWeapon(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
ItemMesh = ObjectInitializer.CreateDefaultSubobject<UStaticMeshComponent>(this, TEXT("Weapon"));
ItemMesh->SetIsReplicated(true);
//ItemMesh->mes
RootComponent = ItemMesh;
PrimaryActorTick.bCanEverTick = true;
bReplicates = true;
bNetUseOwnerRelevancy = true;
SetRemoteRoleForBackwardsCompat(ROLE_SimulatedProxy);
bReplicateMovement = true;
}
void ABaseWeapon::SetOwner(APSETPCCharacter* NewOwningPawn)
{
OwningPawn = NewOwningPawn;
}
void ABaseWeapon::OnEquip()
{
/** Do weapon equip things bla */
OnWeaponSpawn();
}
void ABaseWeapon::OnWeaponSpawn()
{
GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, "QWeqwe");
ItemMesh->AttachTo(OwningPawn->GetMesh(), FName(TEXT("WeaponSocket_Rifle")));
}
void ABaseWeapon::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME(ABaseWeapon, OwningPawn);
}