Unity Netcode for GameObjects, 특정 클라이언트에게만 RPC 보내기

특정 클라이언트에게 데이터 전송하기

기본적으로 Netcode에서 제공하는 ClientRpc는 모든 클라이언트에게 데이터를 전송하는 방식입니다. 

출처 - https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/clientrpc/

 

하지만 경우에 따라서는 '특정' 클라이언트에게만 데이터를 전송해야 할 때가 있습니다. 이럴 때 사용할 수 있는 것이 바로 ClientRpcSendParameters입니다!

아래는 ClientRpcSendParameters를 이용하여 특정 클라이언트에게만 데이터를 전송하는 예제 코드입니다.

private void DoSomethingServerSide(int clientId)
{
    if (!IsServer) return;

    // 주의! 미리 알고 있는 ClientId 리스트가 있고, 변경이 필요 없는 경우,
    // 이 함수를 실행할 때마다 메모리 할당을 피하기 위해 이를 캐싱(멤버 변수로)하는 것을 고려해보세요.
    ClientRpcParams clientRpcParams = new ClientRpcParams
    {
        Send = new ClientRpcSendParams
        {
            TargetClientIds = new ulong[]{clientId}
        }
    };

    int randomInteger = Random.Range(0, 7);
    DoSomethingClientRpc(randomInteger, clientRpcParams);
}

[ClientRpc]
private void DoSomethingClientRpc(int randomInteger, ClientRpcParams clientRpcParams = default)
{
    if (IsOwner) return;

    Debug.LogFormat("GameObject: {0} has received a randomInteger with value: {1}", gameObject.name, randomInteger);
}

ClientRpcParam 캐싱하는 방법

private ClientRpcParams clientRpcParams;

private void Start()
{
    clientRpcParams = new ClientRpcParams
    {
        Send = new ClientRpcSendParams
        {
            TargetClientIds = new ulong[1] // 생각하는 최대 타겟 클라이언트 크기
        }
    };
}

private void DoSomethingServerSide(int clientId)
{
    if (!IsServer) return;

    // 타겟 클라이언트 ID 설정
    clientRpcParams.Send.TargetClientIds[0] = clientId;
	...이하 생략
    
}