I'm fairly new to unity networking and Networking itself.
Game: I have 2 players multiplayer game where each player can shoot.
Problem:
Code 1 makes both players shoot (in the host game only) when host player press spacebar. The client player cannot shoot from the client's game.
Note: the if (Input.GetKeyDown (KeyCode.Space))
is inside the CmdShoot method.
Code 2 executes correctly. Host can shoot in the host game and the client can shoot from the client's game.
Note: the if (Input.GetKeyDown (KeyCode.Space))
is outside the CmdShoot method for code 2.
Question: In code 1, why can't the client shoot and why does host makes both player shoot?
Code 1:
// Update is called once per frame
void Update () {
if (!isLocalPlayer) {
return;
}
CmdShoot ();
}
[Command]
void CmdShoot(){
if (Input.GetKeyDown (KeyCode.Space)) {
GameObject force_copy = GameObject.Instantiate (force) as GameObject;
force_copy.transform.position = gameObject.transform.position + gameObject.transform.forward;
force_copy.GetComponent<Rigidbody>().velocity = gameObject.transform.forward * force.GetComponent<Force>().getSpeed();
NetworkServer.Spawn (force_copy);
Destroy (force_copy, 5);
}
}
Code 2:
// Update is called once per frame
void Update () {
if (!isLocalPlayer) {
return;
}
if (Input.GetKeyDown (KeyCode.Space)) {
CmdShoot ();
}
}
[Command]
void CmdShoot(){
GameObject force_copy = GameObject.Instantiate (force) as GameObject;
force_copy.transform.position = gameObject.transform.position + gameObject.transform.forward;
force_copy.GetComponent<Rigidbody>().velocity = gameObject.transform.forward * force.GetComponent<Force>().getSpeed();
NetworkServer.Spawn (force_copy);
Destroy (force_copy, 5);
}
The [Command]
tag tells that client wants to execute this function on a server.
In Code 1 case, your code calls the CmdShoot()
to execute on server and then check if server is holding Space down (thus only host is able to shoot everything and client(s) not able to shoot at all).
In Code 2 case, your code first checks if local program is holding Space key down (independent of being host or client). If the local program is holding space key then it calls the CmdShoot()
on server.