Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Join us on March 30, 2023, between 5 am & 1 pm EST, in the Performance Profiling Dev Blitz Day 2023 - Q&A forum and Discord where you can connect with our teams behind the Memory and CPU Profilers.
    Dismiss Notice

Question Once a variable change, call the function

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

  1. jerermyzhou


    Aug 24, 2020
    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


    Mar 26, 2013
    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
    4. void Update()
    5. {
    6.     if (mySyncedString != mySyncedStringOld)  //Check if mySyncedString has changed
    7.     {
    8.         callMeWhenStringChanges();  //It changed, so call some function
    9.     }
    10. }
    12. void callMeWhenStringChanges()
    13. {
    14.     //Do something useful here I assume
    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


    Jun 16, 2013
    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.