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);
}