0
votes

I have this problem and i don't know how to solve it,it's very confusing.I want that every time i instantiate the gameobject it gets a random color, but these clones get the same color from previous one.Like the first prefab spawn and gets random colors, now the next one spawn and olso gets random colors but the first one gets it's color,it's very confusing i know! enter image description here

Here is the code of the gate : public Material[] material; public Color[] colors;

public void ColorChange()
{
    colors = new[] {
    Color.blue,
    Color.black,
    Color.red,
    Color.green,
    Color.yellow,
    Color.white,
    Color.magenta,
    Color.cyan,
    Color.grey };

    var rnd = new System.Random();
    var randomColors = colors.OrderBy(x => rnd.Next()).ToArray();

    for (var i = 0; i < material.Length; i++)
    {
        material[i].color = randomColors[i];

    }

}
private void Start()
{

    ColorChange();
}

And the script of the spawner: public GameObject Gate; // the gameobject

private float timeBtwSpawn;
public float startTimeBtwSpawn;
public float decreaseTime;
public float minTime = 0.65f;

void Start()
{

}
void Update()
{
    if (timeBtwSpawn <= 0)
    {
        Instantiate(Gate, transform.position, Quaternion.identity);

        timeBtwSpawn = startTimeBtwSpawn;
        if (startTimeBtwSpawn > minTime)
        {
            startTimeBtwSpawn -= decreaseTime;
        }

    }
    else
    {
        timeBtwSpawn -= Time.deltaTime;
    }
}
1
try to initialize this at class level var rnd = new System.Random();. I mean make it class member - vivek nuna

1 Answers

0
votes

Materials are shared between GameObjects, so if you change the color of a material - all objects using that material will get the new color.

Here's a few approaches (see the last one for my suggestion):


MaterialPropertyBlock

(Will not work in your case)

You could check out MaterialPropertyBlock:

Use it in situations where you want to draw multiple objects with the same material, but slightly different properties. For example, if you want to slightly change the color of each mesh drawn.

Will not work because you're re-using the materials.


Pre-created set of materials

Work around it by either creating a number of materials and chosing a random one.

(Which is what you have done, but will not work since you're reusing the materials)


New materials in runtime

Or you could create new materials in runtime.

(Should work, but next one is easier)


GameObject's Renderer.material

But I believe the easiest way should be to do:

mySpawnedGameObject.GetComponent<Renderer>().material.color = randomColor;

as opposed to using material.sharedMaterial. This should only apply to the one GameObject you choose: Renderer.material