Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Third Party [PUN2[ Only one client changes value

Discussion in 'Multiplayer' started by kqmdjc8, Sep 28, 2019.

  1. kqmdjc8

    kqmdjc8

    Joined:
    Jan 3, 2019
    Posts:
    102
    Hello, I have a problem that only one client seems to affect a value in script. Here is the enemy script

    Code (CSharp):
    1. float health;
    2.     public void Update()
    3.     {
    4.         DisplayHealth();
    5.     }
    6.     public void DisplayHealth()
    7.     {
    8.         healthText.text = health.ToString();
    9.     }
    10.     public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
    11.     {
    12.         if (stream.IsWriting)
    13.         {
    14.             stream.SendNext(health);
    15.         }
    16.         else
    17.         {
    18.             this.health = (float)stream.ReceiveNext();
    19.         }
    20.     }
    And here is the bullet script (bullet is instantiated by player and specific player is owner - I've read that only one player should check for collisions - that's why there is this if(photonView.IsMine))

    Code (CSharp):
    1. private void OnCollisionEnter2D(Collision2D collision)
    2.     {
    3.         if (!photonView.IsMine) return;
    4.         if (collision.gameObject.tag == "Enemy")
    5.         {
    6.             collision.gameObject.GetComponent<EnemyController>().health -= 10;
    7.         }
    8.     }
    When one player shoots enemy health updates on all clients. When another player shoots enemy then health changes and goes back to previous value.
     
  2. kqmdjc8

    kqmdjc8

    Joined:
    Jan 3, 2019
    Posts:
    102
    I'd like to add that if I remove this from collision checking
    Code (CSharp):
    1. if (!photonView.IsMine) return;
    then the value syncs between all clients but is glitchy and jumps like crazy but after all it displays propper value
     
  3. kqmdjc8

    kqmdjc8

    Joined:
    Jan 3, 2019
    Posts:
    102
    SOLVED: I've started using RPCs and it works like a dream but I still have no clue what I was doing wrong.
     
  4. tobiass

    tobiass

    Joined:
    Apr 7, 2009
    Posts:
    3,079
    Guessing here: You tried to update the enemy's health in OnCollisionEnter2D. However, the enemy is likely not under your control, so the other player's client gets to send the health value. Meaning: Nobody can change "my" health directly. Anyone who wants to do that has to send an RPC to me, so I change it and send the new value.