Increase or decrease room property value

Options
Hi! I am working at a team based game and I'm storing the teams score in room properties, this is the code to increase/decrease the score value:
ExitGames.Client.Photon.Hashtable prop = new ExitGames.Client.Photon.Hashtable();

 object currentScore;
 int deltaScore= 5;
 if (PhotonNetwork.CurrentRoom.CustomProperties.TryGetValue("TeamScore", out currentScore))
 {
     int totalScore = (int)currentScore+ deltaScore;
     prop.Add("Score", totalScore);
 }
 PhotonNetwork.CurrentRoom.SetCustomProperties(prop);

A problem occurs when there are 2 or more client scoring a point almost at the same time, the value I get with TryGetValue is the same for both, even if the method can't be called on both clients at the very same time, the time interval is still not enough to have the property synced. As result, only one of the client's score is added to the total team score (overwriting the other increase).

Is there a workaround to this?

I was thinking at having a system with the score stored in the master client and get it synced through RaiseEvent or something similar, nevertheless in this case I would lose the convenience I had with the room properties.

Comments

  • Spygapp
    Options
    well, I found a way with expectedProperty. In case someone will have a similar problem, here the code:
    
    int tempTotalScore;
    
    void updateProperty(int score){
       ExitGames.Client.Photon.Hashtable prop = new ExitGames.Client.Photon.Hashtable();
       ExitGames.Client.Photon.Hashtable expectedProp = new ExitGames.Client.Photon.Hashtable();
    
       object currentScore;
       int deltaScore= score;
       if (PhotonNetwork.CurrentRoom.CustomProperties.TryGetValue("TeamScore", out currentScore))
       {
           expectedProp=(int)currentScore
           int totalScore = (int)currentScore+ deltaScore;
        
           //you will need this later, in case of error
           tempTotalScore=totalScore
         
           prop.Add("Score", totalScore);
        }
        //the property is updated only if the current value is still expectedProp
        PhotonNetwork.CurrentRoom.SetCustomProperties(prop,expectedProp);
    
    }



    Also, a callback for error and try again is needed:
    public  void OnEnable()
    {
        PhotonNetwork.NetworkingClient.OpResponseReceived += NetworkingClientOnOpResponseReceived;
    }
    
    public void OnDisable()
    {
        PhotonNetwork.NetworkingClient.OpResponseReceived -= NetworkingClientOnOpResponseReceived;
    }
    
    private void NetworkingClientOnOpResponseReceived(OperationResponse opResponse)
    {
          if (opResponse.OperationCode == OperationCode.SetProperties &&
              opResponse.ReturnCode == ErrorCode.InvalidOperation)
          {
               updateProperty(tempTotalScore);
          }
    }
    
  • Tobias
    Options
    Nice you're sharing. Thanks!