I'm trying to generate a random key and share it with other players using RPC.

This is the code that i'm currently using, i've tried may different logic but it's no use. Can someone please point out the problem? i think i'm using the RPC wrong.

public class GeneratingKey : Photon.MonoBehaviour {
int random;
string key = null;
string RandomKey = "";
void Start() {
if(PhotonNetwork.countOfPlayers == 1 && key == null)
{
for (int i = 0; i < 30; i++) {
random = Random.Range (1, 5);
RandomKey = RandomKey + random.ToString();
}
key = RandomKey;
}
if (key != null) {
ProceduralNumberGenerator.SetKey (key);
}
}
void Update(){
photonView.RPC ("SetKey", PhotonTargets.Others, key);
if (key != null)
Debug.Log (key);
ProceduralNumberGenerator.SetKey (key);
}
// Update is called once per frame
[PunRPC]
void SetKey (string tempString) {
if (key == null) {
key = tempString;
}
}
}

Answers

  • Hi @SaneAxe,

    there is one major problem with this code snippet, which however should not prevent it from working properly. You call the RPC function in each Update call. This will result in a lot of wasted bandwidth and traffic. Instead you can call the RPC function once in the Start method and buffer it. Buffering this message can be achieved by using PhotonTargets.OthersBuffered as parameter in the RPC. This way you also make sure, that every client, who joins later, will also receive this RPC. In order to try if the RPC get sent and received properly, you can use PhotonTargets.All instead of *.Others and add a Debug.Log to the SetKey function to see if something gets printed to the console. Later on, you can either switch to *.OthersBuffered or *.AllBuffered.

    Another thing: if you want to make sure, that only one client does something when being in a room, you can also use the PhotonNetwork.isMasterClient condition instead of PhotonNetwork.countOfPlayers == 1. In this case only the MasterClient of the current room will do anything.

    Please let me know if this solves the problem or if it still persists.
  • you must use
    if(PhotonNetwork.countOfPlayers == 0)
    or
    if(PhotonNetwork.room.playerCount == 1)