Search Unity

Help Wanted Once a variable change, call the function

Discussion in 'Multiplayer' started by jerermyzhou, Sep 21, 2020.

  1. jerermyzhou

    jerermyzhou

    Joined:
    Aug 24, 2020
    Posts:
    4
    I am developing a multiplayer game with Photon. There is a string variable. I can change this string variable on my master client. I want to sync the string value to all clients, and as long as string value is updated, another function is invoked.
    For example, I updated this string variable to "Hello there", once the clients receives this change, another function is called. I know RPC call can sync the variable like the code below. However, I don't know how I can invoke another function once the string value changes.

    if (PhotonNetwork.isMasterClient)
    photonView.RPC ("SendMessageRPC", PhotonTargets.All, "Hello there!");



    Thanks for your help.
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,574
    I'm not familiar if Photon has some built in functionality for this (haven't tried Photon for more than a few hours), but you can pretty easily brute force this.

    Code (csharp):
    1. private string mySyncedString = "";   //This string is somehow synced using Photon, RPC I guess
    2. private string mySyncedStringOld = "";  //old value of the synced string we retain for comparison
    3.  
    4. void Update()
    5. {
    6.     if (mySyncedString != mySyncedStringOld)  //Check if mySyncedString has changed
    7.     {
    8.         callMeWhenStringChanges();  //It changed, so call some function
    9.     }
    10. }
    11.  
    12. void callMeWhenStringChanges()
    13. {
    14.     //Do something useful here I assume
    15.  
    16.  
    17.     //Set the old value of the string to the new value so we can check again in future frames for additional changes
    18.     mySyncedStringOld = mySyncedString;
    19. }
     
  3. Munchy2007

    Munchy2007

    Joined:
    Jun 16, 2013
    Posts:
    1,586
    CustomProperties are probably the best way to go with this. There is a callback on all clients whenever a custom property value is changed, so you could call your function in that.
     
unityunity