📑
UE5.4で同一セッション内のプレイヤー間で通信を行う
概要
UE5でオンラインゲームを作成するにあたり、同一セッション内のプレイヤー間で通信を行うための手順についての備忘録になります。
ここでいう通信とは、プレイヤー間で単純なメッセージ(文字列)をやりとりすることを指します。
セッションの仕組みを作成するまで
下記記事を参考に実装しました。
参考 : UE OnlineSubsystemでオンラインマルチプレイを実装する(C++)
プレイヤー間で通信を行う
PlayerStateクラスを継承したC++クラスを作成します。本記事ではこれをMyPlayerStateクラスとして作成しています。
まずはMyPlayerState.hに下記コードを貼り付けてください。
MyPlayerState.h
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/PlayerState.h"
#include "MyPlayerState.generated.h"
UCLASS()
class RSP_TEST_API AMyPlayerState : public APlayerState
{
	GENERATED_BODY()
	
public:
    UFUNCTION(Server, Reliable, WithValidation, BlueprintCallable)
    void ServerSendMessage(const FString& Message);
    UFUNCTION(Client, Reliable)
    void ClientReceiveMessage(const FString& Message, const FString& SenderName);
};
次に、MyPlayerState.cppに下記コードを貼り付けてください。
MyPlayerState.cpp
#include "MyPlayerState.h"
#include "GameFramework/GameStateBase.h"
#include "Engine/World.h"
#include "GameFramework/PlayerController.h"
void AMyPlayerState::ServerSendMessage_Implementation(const FString& Message)
{
    FString SenderName = GetPlayerName(); // 送信者の名前を取得
    // サーバー側で全クライアントにメッセージを送信
    for (APlayerState* PlayerState : GetWorld()->GetGameState()->PlayerArray)
    {
        if (AMyPlayerState* MyPlayerState = Cast<AMyPlayerState>(PlayerState))
        {
            MyPlayerState->ClientReceiveMessage(Message, SenderName);
        }
    }
}
bool AMyPlayerState::ServerSendMessage_Validate(const FString& Message)
{
    return true; // 必要ならバリデーション処理を入れる
}
void AMyPlayerState::ClientReceiveMessage_Implementation(const FString& Message, const FString& SenderName)
{
    UE_LOG(LogTemp, Log, TEXT("Received Message from %s: %s"), *SenderName, *Message);
}
使い方ですが、ServerSendMessage()の引数に設定したメッセージが、セッション内のプレイヤー全てに通知されます(上記コードの実装では、メッセージを送信したプレイヤー名も通知されます)。
ServerSendMessage()はブループリントから呼び出してもOKです。
最後に、GameModeの設定になります。<プロジェクト名>Gamemode.cppに下記のように追記してください。
xxxGamemode.cpp
#include "xxxGameMode.h"
#include "xxxCharacter.h"
#include "UObject/ConstructorHelpers.h"
#include "MyPlayerState.h" // 追記
xxxGameMode::xxxGameMode()
{
	/* ... */
    /* ... */
	PlayerStateClass = AMyPlayerState::StaticClass(); // 追記
}
実行確認
Steamアカウントを分ける必要があるため、PC2台以上を用意して実行してください。
Discussion