장 실습: 함께 여는 보물상자
두 플레이어가 같은 상자를 열도록 휴면·서버 검사·소유자 인벤토리 복제를 연결하고 거리·중복 요청을 확인합니다.
두 플레이어가 같은 상자를 열도록 휴면·서버 검사·소유자 인벤토리 복제를 연결하고 거리·중복 요청을 확인합니다. 코드와 에디터 설정을 함께 확인하고 처음 결과가 달라지는 단계에서 멈춰 비교합니다.
시작 상태
멀티플레이어 게임 최적화까지의 Third Person 템플릿 프로젝트를 씁니다. 레벨에 AMyTreasureChest 하나, BP_ThirdPersonCharacter에 UMyReplicatedComponent를 준비하고 F·E 입력을 연결합니다. RPC와 서버-클라이언트 통신의 연습을 건너뛰었다면 아래 완성 파일과 입력 그래프로 맞춥니다. 두 창 플레이는 Number of Players 2, Play As Listen Server입니다.
완성할 과제
8장에서 만든 부품을 모아, 두 플레이어가 같은 레벨에서 보물상자를 여는 기능을 완성합니다. 상자를 처음 연 플레이어만 인벤토리에 탄약을 받고, 그 사실은 그 플레이어에게만 전달됩니다.
완성 조건은 다음과 같습니다.
- 상자는
DORM_Initial로 휴면 상태에서 시작하고, 열릴 때 깨운 뒤bIsOpened를 바꿉니다. - 서버는 캐릭터와 상자의 거리가 300cm보다 멀면 열지 않고
Too far from the chest를, 이미 열린 상자라면Already opened를 그 플레이어에게만 알립니다. 둘 다 연결을 끊지 않습니다. - 처음 연 플레이어의
PlayerInventory에Ammo를 더하고Chest opened를 알립니다.PlayerInventory는 소유자에게만 복제됩니다.
다음 표의 순서대로 확인합니다. 각 단계의 결과를 먼저 예상하고 플레이해 봅니다.
| 단계 | 하는 일 | 예상 결과 |
|---|---|---|
| 1 | 두 창으로 플레이 시작 | 두 창 모두 상자 위에 Closed, 출력 로그에 [Client] ... inventory: 1 한 줄 |
| 2 | 클라이언트 캐릭터로 상자에서 5m 떨어져 E | 두 창 모두 Closed, [Client] Message: Too far from the chest, 연결 유지 |
| 3 | 클라이언트 캐릭터로 상자 옆에서 E | 두 창 모두 Opened, [Client] ... inventory: 2, [Client] Message: Chest opened |
| 4 | 호스트 캐릭터로 상자 옆에서 E | 상자는 그대로 Opened, [Server] Message: Already opened, 인벤토리 줄 없음 |
힌트: 상자에 열림 상태를 읽는 IsOpened()를 더하면, 컴포넌트가 이미 열린 상자를 구별할 수 있습니다. 인벤토리를 바꾸는 코드는 서버에서 실행되는 Server_OpenChest_Implementation 안에 둡니다.
단계별 체크포인트
체크포인트 1: 휴면과 소유자 복제 연결하기
상자는 DORM_Initial에서 시작하고 값을 바꾸기 전에 깨웁니다. 인벤토리는 소유자에게만 복제하도록 연결합니다.
체크포인트 2: 먼 거리의 요청 거절하기
두 창에서 Closed를 확인한 뒤 클라이언트가 5m 떨어져 E를 누릅니다. 그 플레이어에게 Too far from the chest가 보이고 연결이 유지되어야 합니다.
체크포인트 3: 첫 열기와 두 번째 요청 비교하기
클라이언트가 가까이서 열면 두 창이 Opened이고 소유자에게 inventory: 2가 보입니다. 호스트의 다음 요청은 Already opened이고 인벤토리는 더 늘지 않아야 합니다.
다를 때 먼저 볼 곳
| 증상 | 다를 때 먼저 볼 곳 |
|---|---|
| 1단계에서 인벤토리 줄이 없다 | 캐릭터 블루프린트의 컴포넌트에서 Component Replicates가 켜져 있는지 |
| 2단계에서 클라이언트 연결이 끊긴다 | 거리 검사를 _Validate가 아니라 _Implementation에 두었는지 |
3단계에서 서버만 Opened다 | Open()에서 FlushNetDormancy()가 bIsOpened 대입보다 앞에 있는지 |
3단계에서 inventory: 2가 없다 | PlayerInventory.Add가 Server_OpenChest_Implementation 안에 있는지, 이미 열린 상자가 아닌지 |
| E를 눌러도 서버 로그와 메시지가 모두 없다 | 그래프의 E 노드가 Request Open Chest에 이어져 있는지, 레벨에 상자가 있는지 |
완성 파일
완성 파일과 확인 순서 보기
상자에서 바뀌는 곳은 휴면 설정, FlushNetDormancy(), IsOpened()입니다. 컴포넌트의 Server_OpenChest_Implementation은 검사 두 개(거리, 이미 열림)를 정상적인 게임상 거절로 처리하고, 통과하면 상자를 열고 인벤토리를 바꿉니다. 서버에서 PlayerInventory를 바꾸면 소유 클라이언트에서만 OnRep_PlayerInventory가 불려 inventory: 2가 찍힙니다.
4단계에서 인벤토리 줄이 없는 이유는 두 가지입니다. 상자가 이미 열려 있어 Ammo를 더하지 않았고, 호스트는 서버이므로 더했더라도 서버의 OnRep_는 저절로 불리지 않습니다. 호스트가 먼저 상자를 열면 [Server] Message: Chest opened가 찍히고 두 창의 상자가 Opened가 되며, 이때도 인벤토리 줄은 찍히지 않습니다.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "MyTreasureChest.generated.h"
class UStaticMeshComponent;
class UTextRenderComponent;
UCLASS()
class MYPROJECT_API AMyTreasureChest : public AActor
{
GENERATED_BODY()
public:
AMyTreasureChest();
virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
void Open();
bool IsOpened() const { return bIsOpened; }
protected:
UPROPERTY(VisibleAnywhere, Category = "Chest")
TObjectPtr<UStaticMeshComponent> Mesh;
UPROPERTY(VisibleAnywhere, Category = "Chest")
TObjectPtr<UTextRenderComponent> Label;
UPROPERTY(ReplicatedUsing = OnRep_IsOpened)
bool bIsOpened = false;
UFUNCTION()
void OnRep_IsOpened();
};#include "MyTreasureChest.h"
#include "Components/StaticMeshComponent.h"
#include "Components/TextRenderComponent.h"
#include "Engine/StaticMesh.h"
#include "Net/UnrealNetwork.h"
#include "UObject/ConstructorHelpers.h"
AMyTreasureChest::AMyTreasureChest()
{
PrimaryActorTick.bCanEverTick = false;
bReplicates = true;
NetDormancy = DORM_Initial;
Mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
RootComponent = Mesh;
static ConstructorHelpers::FObjectFinder<UStaticMesh> CubeMesh(TEXT("/Engine/BasicShapes/Cube.Cube"));
if (CubeMesh.Succeeded())
{
Mesh->SetStaticMesh(CubeMesh.Object);
}
Label = CreateDefaultSubobject<UTextRenderComponent>(TEXT("Label"));
Label->SetupAttachment(Mesh);
Label->SetRelativeLocation(FVector(0.f, 0.f, 80.f));
Label->SetHorizontalAlignment(EHTA_Center);
Label->SetText(FText::FromString(TEXT("Closed")));
}
void AMyTreasureChest::Open()
{
if (!HasAuthority() || bIsOpened)
{
return;
}
FlushNetDormancy();
bIsOpened = true;
OnRep_IsOpened();
}
void AMyTreasureChest::OnRep_IsOpened()
{
Label->SetText(FText::FromString(bIsOpened ? TEXT("Opened") : TEXT("Closed")));
}
void AMyTreasureChest::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME(AMyTreasureChest, bIsOpened);
}#pragma once
#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "MyReplicatedComponent.generated.h"
class AMyTreasureChest;
UCLASS(ClassGroup = (Custom), meta = (BlueprintSpawnableComponent))
class MYPROJECT_API UMyReplicatedComponent : public UActorComponent
{
GENERATED_BODY()
public:
UMyReplicatedComponent();
virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
UFUNCTION(BlueprintCallable, Category = "Combat")
void RequestShoot();
UFUNCTION(BlueprintCallable, Category = "Chest")
void RequestOpenChest();
protected:
virtual void BeginPlay() override;
UPROPERTY(ReplicatedUsing = OnRep_PlayerInventory)
TArray<FString> PlayerInventory;
UFUNCTION()
void OnRep_PlayerInventory();
UFUNCTION(Server, Reliable, WithValidation)
void Server_ShootWeapon(FVector MuzzleLocation);
UFUNCTION(NetMulticast, Unreliable)
void Multicast_PlayExplosionEffect(FVector ExplosionLocation);
UFUNCTION(Client, Reliable)
void Client_ShowMessage(const FString& Message);
UFUNCTION(Server, Reliable)
void Server_OpenChest(AMyTreasureChest* Chest);
};#include "MyReplicatedComponent.h"
#include "DrawDebugHelpers.h"
#include "Kismet/GameplayStatics.h"
#include "MyTreasureChest.h"
#include "Net/UnrealNetwork.h"
namespace
{
const TCHAR* NetTag(const AActor* Actor)
{
return Actor->GetNetMode() == NM_Client ? TEXT("Client") : TEXT("Server");
}
}
UMyReplicatedComponent::UMyReplicatedComponent()
{
SetIsReplicatedByDefault(true);
}
void UMyReplicatedComponent::BeginPlay()
{
Super::BeginPlay();
if (GetOwner()->HasAuthority())
{
PlayerInventory.Add(TEXT("Pistol"));
}
}
void UMyReplicatedComponent::OnRep_PlayerInventory()
{
UE_LOG(LogTemp, Warning, TEXT("[%s] %s inventory: %d"), NetTag(GetOwner()), *GetOwner()->GetName(), PlayerInventory.Num());
}
void UMyReplicatedComponent::RequestShoot()
{
const FVector Muzzle = GetOwner()->GetActorLocation() + GetOwner()->GetActorForwardVector() * 100.f;
Server_ShootWeapon(Muzzle);
}
bool UMyReplicatedComponent::Server_ShootWeapon_Validate(FVector MuzzleLocation)
{
if (MuzzleLocation.ContainsNaN())
{
return false;
}
return FVector::DistSquared(GetOwner()->GetActorLocation(), MuzzleLocation) <= FMath::Square(500.f);
}
void UMyReplicatedComponent::Server_ShootWeapon_Implementation(FVector MuzzleLocation)
{
UE_LOG(LogTemp, Warning, TEXT("[%s] Server_ShootWeapon at %s"), NetTag(GetOwner()), *MuzzleLocation.ToString());
Multicast_PlayExplosionEffect(MuzzleLocation);
Client_ShowMessage(TEXT("Shot accepted"));
}
void UMyReplicatedComponent::Multicast_PlayExplosionEffect_Implementation(FVector ExplosionLocation)
{
DrawDebugSphere(GetWorld(), ExplosionLocation, 30.f, 12, FColor::Red, false, 1.f);
}
void UMyReplicatedComponent::Client_ShowMessage_Implementation(const FString& Message)
{
UE_LOG(LogTemp, Warning, TEXT("[%s] Message: %s"), NetTag(GetOwner()), *Message);
}
void UMyReplicatedComponent::RequestOpenChest()
{
AMyTreasureChest* Chest = Cast<AMyTreasureChest>(UGameplayStatics::GetActorOfClass(this, AMyTreasureChest::StaticClass()));
if (Chest)
{
Server_OpenChest(Chest);
}
}
void UMyReplicatedComponent::Server_OpenChest_Implementation(AMyTreasureChest* Chest)
{
if (!Chest)
{
return;
}
if (FVector::Dist(GetOwner()->GetActorLocation(), Chest->GetActorLocation()) > 300.f)
{
Client_ShowMessage(TEXT("Too far from the chest"));
return;
}
if (Chest->IsOpened())
{
Client_ShowMessage(TEXT("Already opened"));
return;
}
Chest->Open();
PlayerInventory.Add(TEXT("Ammo"));
Client_ShowMessage(TEXT("Chest opened"));
}
void UMyReplicatedComponent::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME_COND(UMyReplicatedComponent, PlayerInventory, COND_OwnerOnly);
}AMyReplicatedActor는 복제(Replication) 시스템 이해 끝의 전체 파일 그대로이며 이 과제에서 바꾸지 않습니다. 블루프린트 그래프는 다음 두 줄이 이어져 있으면 됩니다.
[F] (Keyboard Events) Pressed ──▶ [Request Shoot] Target ◀── [MyReplicated]
[E] (Keyboard Events) Pressed ──▶ [Request Open Chest] Target ◀── [MyReplicated]에디터를 닫고 Development Editor로 빌드한 뒤 다시 열고, 표의 1단계부터 4단계까지 차례로 확인합니다.
더 해 보기
- 상자를 연 뒤 10초가 지나면 서버가 다시 닫게 합니다. 이미 깨운 상자이므로 휴면 상태를
DORM_Initial로 되돌리지 말고, 값을 바꾸기 전에 다시 깨우는 순서를 지킵니다. - 인벤토리에
Ammo가 있을 때만 F로 쏠 수 있게 하고, 쏠 때마다 하나씩 줄입니다. 탄약 확인과 차감은 서버에서 합니다. - 상자를 연 플레이어의 이름을 상자 위 글자에 함께 띄워, 두 창 모두에서 누가 열었는지 보이게 합니다.
네트워크 트레이스와 분석 방법은 Epic의 Networking Insights 문서에서, 휴면 상태와 깨우는 방법은 Actor Network Dormancy 문서에서 확인할 수 있습니다.
이것으로 8장을 마칩니다. 8장에서는 두 창으로 띄운 리슨 서버에서 역할과 소유권을 확인하고, 변수와 컴포넌트를 복제하고, RPC로 요청과 결과를 주고받고, 휴면으로 복제 비용을 줄이며 보물상자를 완성했습니다. 다음 장의 프로파일링 도구 사용법부터는 게임 전체의 성능을 측정하고, 메모리, 렌더링, CPU와 GPU의 병목을 찾아 해결하는 방법을 다룹니다.