- Home /
Assign a random material to objects
I have 5 objects in my scene and 5 materials, what I would like is for every time the scene starts, the objects will have a random material based on the 5 materials. I would only like each material to be used once. I have this so far:
public Material[] randomMaterials;
public GameObject[] coloredWalls;
void Start ()
{
foreach(Material materials in randomMaterials)
{
//randomMaterial[materials] = Random.Range (0, 5);
foreach(GameObject wall in coloredWalls)
{
wall.renderer.material = materials;
}
}
}
I have it assigning a material at the moment, but as it iterates through the foreach loop without assigning a random value, all of the objects are always the last material in the array.
I tried giving the material a random value using the Random.Range, but unity doesn't seem to like that. If anyone could give me a hand I'd appreciate it.
Answer by zharik86 · Aug 24, 2014 at 10:59 AM
As far as I understood, you apply an random material to each object in case of initialization. The code sample is lower:
public Material[] randomMaterials;
public GameObject[] coloredWalls;
void Start () {
foreach(GameObject wall in coloredWalls) { //see all objects
//Assign random material to object
wall.renderer.material = randomMaterials[Random.Range(0, randomMaterials.Length)];
}
}
I hope that it will help you.
Hi @zharik86, yes that works much better, thank you :) Just a small thing, is there a way using this method that I could use each material only once?
At the moment, when I play, sometimes, 2 or more objects can have the same material
@RandomUser123 I understood, materials will have no recurrence. I will rewrite a script of the response with adding of new comments:
public $$anonymous$$aterial[] random$$anonymous$$aterials;
public GameObject[] coloredWalls;
void Start () {
//Simple way: create int array for indicate assign material
int[] ind$$anonymous$$at = new int[random$$anonymous$$aterials.Length];
//Just in case we initialize an array
for(int i = 0; i < random$$anonymous$$aterials.Length; i++) {
ind$$anonymous$$at[i] = 0; //not assign material
}
foreach(GameObject wall in coloredWalls) { //see all objects
//Assign random material to object
int num = Random.Range(0, random$$anonymous$$aterials.Length);
//already apply, find next
while(ind$$anonymous$$at[num] != 0) {
num++;
if (num >= random$$anonymous$$aterials.Length) {
num = 0;
}
}
ind$$anonymous$$at[num] = 1;
wall.renderer.material = random$$anonymous$$aterials[num];
}
}
Wow, this works great, I would have never gotten this ha :( maybe one day :)
Anyway, thank you so much for your time, I appreciate it :)
@RandomUser123 At your service, but you remember that the count of materials shall be more or equal count of objects, differently there will be an infinite cycle.
Your answer
![](https://koobas.hobune.stream/wayback/20220613161412im_/https://answers.unity.com/themes/thub/images/avi.jpg)