- Home /
UNET - Why is my NetworkInstanceID equal on both clients when receiving ClientRpc?
Hi!
I'm currently playing around with a simple chat system for my gamelobby.
My Setup:
I'm using HLAPI like so:
//this is called on client within my LobbyPlayer class which inherits from LobbyNetworkPlayer
public void SendMessage(string msg){
CmdSendChatMessage(msg, netId.Value);
}
//this should be triggered by the client, but executed by the server
[Command]
public void CmdSendChatMessage(string message, uint senderID)
{
Debug.Log("client "+senderID+" sent a message");
}
//this should be triggered by the server but executed by the client
[ClientRpc]
public void RpcReceiveChatMessage(string message, uint senderID)
{
Debug.Log("client "+netId.Value+" received message from:"+senderID);
}
As you can see, I send the netId.Value of the respective sending player along with the message. I need this to determine which client sent the message, when another (or same) client receives it.
The problem:
My problem is best explained by an example: If client A triggers sending a message, the Server forwards the Message to client A and B, which is fine. However, both clients seem to have the same netId.Value upon receiving the message:
//Output when client A sends a message:
[Server]: Client 1 sent a message
[A]: Client 1 received message from: 1 //this is expected
[B]: Client 1 received message from: 1 //this should be "Client 2 received message from: 1"
The same thing happens when client B triggers sending a message, but then the netId is 2 (on both clients). So it seems, both LobbyPlayers have different netIds, but when they receive the message from the server, their netId is the id of the sender.
The Question:
Why is that? Shouldn't it be like I expected? Or is there a better way to determine which player sent the message?
Cheers, phineliner
Answer by phineliner · Nov 23, 2015 at 05:44 PM
Alright,
there is no problem with the code, but there was a problem with my understanding of how ClientRpc works. For whatever reason I thought that calling the SendMessage on PlayerObject A would cause the server to call the RpcReceiveChatMessage on PlayerObject B. This, of course, is not the case, so that the Rpc is called on PlayerObject A. And that's why the netId is always the same -> because it is the same object.
To determine which PlayerObject sent the message, you would have to iterate over all player objects of the lobby and compare their netId with the sender id. If you simply would like to check if the message was sent from the local client or a remote client, you could just check for "isLocalPlayer" in the Rpc method.
Hope this helps somebody else.
Cheers phineliner