Cloned objects choosing different colors
I have a game were a grid will spawn and i need the colors of each cube on the grid to randomize but everyone of them is a clone, currently when i press start simulation the cubes will go on flashing or will be all white or black (occasionally they will be half and half like their supposed to) what am i doing wrong?
code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class Wall : MonoBehaviour {
//get random
System.Random rdn;
//clone temp random
private int _tempRnd;
//textures
public Texture2D White;
public Texture2D Black;
void Start () {
//pick random and then input into clone temp random
rdn = new System.Random();
_tempRnd = rdn.Next(1, 3);
// send log for viewing
Debug.Log(_tempRnd);
//pick the number anc choose
if (_tempRnd == 1)
{
GetComponent<Renderer>().material.mainTexture = White;
}
else
{
GetComponent<Renderer>().material.mainTexture = Black;
}
}
}
Answer by Harinezumi · Apr 20, 2018 at 07:35 AM
This is just a theory, but I think the problem is that you are using a separate System.Random
object in each instance of the Wall script and get their Start()
method called on the same frame. That way System.Random
objects get initialized with the same seed, so rdn.Next()
will return the same value for all. When it is half-half, some of the Wall scripts get their Start()
called on a different frame.
To solve this, either use Unity's built-in randomizer ( UnityEngine.Random
) or make rdn
static and only assign it the first time, when it is null
. If you don't have a special reason to use System.Random
, then just go with UnityEngine.Random
, like this:
// don't need to instantiate UnityEngine's Random
_tempRnd = Random.Range(1, 3); // will return 1 or 2
// the rest is the same; although now you don't need rdn variable
I'm glad it did! :) If you think it would help others as well, you can accept the answer.
Your answer
![](https://koobas.hobune.stream/wayback/20220612161146im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Random.Range code problem or problem with Unity? 1 Answer
Hello there I have a Instantiate Issue 0 Answers
Random AudioClip by their names,Random Clip 0 Answers
Instantiate a prefab and access sub-mesh material 0 Answers
Random colors? 0 Answers