I’m working on a Multiplayer game where at certain parts I use RPC calls to run a part of code in parallel to all the machines connected to my game. Some part of this code uses Random.Range function within which returns different values when running on different machines and hence fails in synchronization.
Part of code that runs in parallel
int rand;
int randNonServer;
if (PlayerPrefs.GetString("GameType") == "Multiplayer")
{
if (PlayerSync.GetLocalPlayerSync().isServer)
{
//Find a random child
randChild = Random.Range(0, transform.childCount);
PlayerSync.GetLocalPlayerSync().SendRand( rand);
StartCoroutine(Wait());
}
else
{
StartCoroutine(Wait());
//Get the random value set by server
rand = randNonServer;
}
}
else
{
//Find a random child
rand = Random.Range(0, transform.childCount);
}
Coroutine
private IEnumerator Wait()
{
yield return new WaitForSeconds(0.5f);
//yield return new WaitUntil(() => randNonServer != -1);
}
In the above code, server sets a random number(int rand) & sends this number to all non server machines which updates int randNonServer. Since this code is running in parallel, on all the non server machines by the time I receive any value on randNonServer my code has already completed its execution using default value of randNonServer. Using Coroutines to wait until I get a value in this variable doesn’t work either.