Syncing SetActive over network
I am trying to implement switching between two weapons. My method is currently:
1) Player prefab has both weapons as children. The first one is active while the second one is inactive to begin with.
2) When a player presses the switch weapon button ('R'), the second one becomes active and the first one become inactive (and vice versa).
When the host presses 'R', it calls RpcToggleWeapon() to toggle its weapon for all clients. When a client presses 'R', it calls CmdToggleWeapon() to make the server call RpcToggleWeapon(), to toggle its weapon for all clients (host included).
My problem:
If a client connects after a host/client already switched weapons, it will not register on the new client.
e.g.
Host starts game.
Client1 connects.
Client1 presses 'R'. Weapon is changed correctly on Host and Client1.
Client2 connects, but sees the wrong weapon for Client1.
Question 1)
Is my method of client2client communication correct? (call cmd to server then have it call rpc to all other clients) I feel there is a better way to sync SetActive...
Question 2)
If my method is the best way, how can I fix the issue described above?
I've attached some code for reference,
void Update () {
if (!isLocalPlayer) return;
if (Input.GetKeyDown(KeyCode.R)){
if (!isServer) { // Client
CmdToggleWeapon();
} else { // Host
RpcToggleWeapon();
}
}
}
[Command]
void CmdToggleWeapon(){
RpcToggleWeapon();
}
[ClientRpc]
void RpcToggleWeapon(){
for (int i = 0; i < weapons.Length; i++) {
weapons[i].gameObject.SetActive(!weapons[i].gameObject.activeSelf);
}
}
Thanks!
I'm not sure about this. But is the [Command] to [ClientRpc]chaining really necessary? As I understand it [Command] sends a funtion to be run at the server, using the clients data. [ClientRpc] sens a function to be run at clients, using the server data. So what you tell the game is: Tell the server to run this function on all clients, using the server data. So it's weird that it works at all, since it should be using the weapons[] that is on the server and not on the client. Am I wrong in this? Oh, and btw, you should probably try to sync the weapon change and have a separate "weapon update"-script. If you [SyncVar] GameObject weapon; Then new clients should recieve the update automatically. After that you just have to update the weapons locally.