My game is separated in Server and Client versions and I have succesfully established a connection between these two Unity instances. Now how can the server version of the game start a method in the Client? Let’s say on Server I have GameManager.cs where to start a method (in client) InstantiateCards() in ClientManager.cs file which is in Cube-named gameobject. Any example maybe? Thank you?
or can anyone provide me with help understanding a simple RPC calls of NetCode? All I’m looking for is a simple RPC on the server side to call a function on the client. The docs seem to only provide more complex ones, listening for input if I understand it right…
Here is a server system that detects when a player disconnects, and the broadcasts an RPC to all clients to notify. them.
public class ServerDetectDisconnectSystem : ComponentSystem {
protected override void OnUpdate() {
Entities
.ForEach((ref NetworkIdComponent networkIdComponent, ref NetworkStreamDisconnected networkStreamDisconnected, ref PlayerID playerID) => {
DebugUtilities.ServerLog(
$"Disconnect detected, netID:{networkIdComponent.Value} playerID: {playerID.Value}, Time: {Time.ElapsedTime} ");
NativeArray<Entity> networkConnections = EntityManager.CreateEntityQuery(typeof(NetworkIdComponent)).ToEntityArray(Allocator.TempJob);
if (networkConnections.Length <= 1) {
DebugUtilities.ServerLog($"No one to broadcast disconnect to.");
}
else {
BroadCastLeftConnection(playerID.Value, networkIdComponent.Value);
}
networkConnections.Dispose();
});
}
void BroadCastLeftConnection(FixedString512 playerID, int networkID) {
var connectionBroadcastEntity = PostUpdateCommands.CreateEntity();
PlayerLeftCommand playerLeftCommand = new PlayerLeftCommand
{
PlayerNetworkID = networkID,
PlayerID = playerID
};
PostUpdateCommands.AddComponent(connectionBroadcastEntity, playerLeftCommand);
PostUpdateCommands.AddComponent(connectionBroadcastEntity, new SendRpcCommandRequestComponent());
}
}
Here’s the actual RPC command object
public struct PlayerLeftCommand : IRpcCommand {
public int PlayerNetworkID;
public FixedString512 PlayerID;
}
Here is the client side code that receives the RPC and then fires an event to the the rest of my program.
[UpdateInGroup(typeof(ClientSimulationSystemGroup))]
public class ClientReceivePlayerLeftBroadcastSystem : ComponentSystem {
protected override void OnUpdate() {
Entities.ForEach((Entity entity, ref PlayerLeftCommand playerLeftCommand,
ref ReceiveRpcCommandRequestComponent req) => {
PostUpdateCommands.DestroyEntity(entity);
NetworkIdComponent networkIdComponent = GetSingleton<NetworkIdComponent>();
bool isThisClient = playerLeftCommand.PlayerNetworkID == networkIdComponent.Value;
DebugUtilities.ClientLog($"Server notifying that {playerLeftCommand.PlayerID} Left. NetID :{playerLeftCommand.PlayerNetworkID} is this self?: {isThisClient}");
if (!isThisClient) ConversationEvents.PlayerLeft(playerLeftCommand.PlayerID.ToString());
});
}
}