Search Unity

Detecting when the other player presses a button

Discussion in 'Multiplayer' started by blestemee, Mar 19, 2017.

  1. blestemee

    blestemee

    Joined:
    May 1, 2014
    Posts:
    2
    I am making a 2 player multiplayer game and I need to detect when the other player presses a button, and when he presses the button it needs to change my current position, however it doesn't work and i can't figure why.

    Here is the script i wrote:

    Code (CSharp):
    1. public class Change : NetworkBehaviour {
    2.      public GameObject player; // reference to the other player
    3.      [SyncVar(hook="Activate")] bool activate=false;
    4.      void Start()
    5.      {
    6.          if(!isLocalPlayer)
    7.          {
    8.              //Destroy(this);
    9.              return;
    10.          }
    11.           if (this.name == "Red(Clone)")
    12.          {
    13.              player = GameObject.Find("Green(Clone)");
    14.          }
    15.          else
    16.          {
    17.              player = GameObject.Find("Red(Clone)");
    18.          }
    19.      }
    20.      [RPC]
    21.      void Activate(bool act)
    22.      {
    23.          activate = act;
    24.      }
    25.      void FixedUpdate()
    26.      {
    27.      
    28.             if(Input.GetKey(KeyCode.E))
    29.          {
    30.              player.GetComponent<Change> ().activate = true;
    31.              player.transform.position = new Vector3 (20f, 20f);
    32.      }
    33.          else
    34.          {
    35.              player.GetComponent<Change> ().activate = false;
    36.           }
    37.            
    38.        
    39.      }
    The player seems to receive the button press only when it is received from the client, however the position is not updated. I would appreciate any help. Thanks
     
  2. blestemee

    blestemee

    Joined:
    May 1, 2014
    Posts:
    2
    Can anyone give any hints please? I've been trying different methods with no success for over 2 weeks now
     
  3. MichalBUnity

    MichalBUnity

    Unity Technologies

    Joined:
    May 9, 2016
    Posts:
    18
    Hi,

    Looking at your code snippet i might have spotted 2 potential issues with it.

    Depending on how you spawn your players, the issue might be that when the LocalPlayer(Host) is spawned and it runs Start() it can't find the other player because its not spawned yet. That would explain why it works for the client but not the server.

    Secondly you cant move another player you don't have authority over due to how the API is designed. You can try to read up a bit of the concepts here https://docs.unity3d.com/Manual/UNetConcepts.html