- Home /
Using Random.seed to sync random generation in multiplayer (android GPGS)
Hi, I am having issues using a random seed to randomly generate a game that is the same on both clients in a Google Play Games Services Real Time multiplayer room. There are cubes that rotate around a circle. At a point along the rotation, they hit a trigger which changes their distance away from the circle individually:
The code that does it is here:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class EnemyAi : MonoBehaviour {
public GameObject Earth,coin;
Vector3 startPos;
public float randMax;
bool isVisible;
public float z;
public List<Transform> spawnPosCoin;
public bool multiplay;
public int seed;
// Use this for initialization
void Start () {
startPos = transform.localPosition;
Vector3 diff = Earth.transform.position - transform.position;
diff.Normalize ();
float rot_z = Mathf.Atan2 (diff.y, diff.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(rot_z, Vector3.forward);
Randomize (true);
z = Earth.transform.eulerAngles.z;
}
// Update is called once per frame
void Update () {
particleSystem.startRotation = (z - transform.eulerAngles.z) * Mathf.Deg2Rad;
}
public void Randomize(bool start)
{
transform.localPosition = startPos;
transform.Translate(Vector2.right * Random.Range(0,randMax));
GetComponent<SpriteRenderer> ().color = new Color (Random.value, Random.value, Random.value, 1.0f);
GetComponent<ParticleSystem> ().startColor = GetComponent<SpriteRenderer> ().color;
if(!start)
{
//animation.Play ("enemyFade");
}
}
public void MultiplayerRandomize()
{
Random.seed = seed;
}
void OnTriggerEnter2D(Collider2D col)
{
if(col.tag == "Randomize")
{
Randomize(false);
//coin stuff
int coinChance = Random.Range(0,14);
if(coinChance == 2)
{
GameObject spawnedCoin = Instantiate(coin,spawnPosCoin.ToArray()[Random.Range(0,spawnPosCoin.Count)].position, Quaternion.identity) as GameObject;
spawnedCoin.transform.parent = GameObject.FindGameObjectWithTag("CoinSpin").transform;
spawnedCoin.GetComponent<Coin>().Earth = Earth;
}
}
}
}
When a player joins the room, it sends a message to each other player with its System.Environment.TickCount
which is then added to the other players' tick counts creating the same seed for each player. It works to start with, when the game starts, MultiplayerRandomize()
and Randomize()
are called and each cube's distance away from the planet is the same on all clients (tested). But when they hit the trigger and Randomize()
is called again, they are different on both devices. I don't know why this is because they both work to start with and the seed is never changed/set twice.
Anybody got any ideas as to why it doesnt work?
Any help is greatly appreciated, thanks.