Hi, Frds, Im New to unity3d…I have doubt in texture randomly generate… i need each texture randomly generate a equal 4 times. for example ,i have 12 cubes .In that 12 cubes randomly generate the [red texture]=4 times and [green texture]= 4 times and [blue texture]= 4 times.
I worked this script, but no use… one time ,red texture generate (five times),green texture generate (two times) , blue texture generate (five times)…
i need equally time generate.
var rand : int = Random.Range(0,3);
switch(rand)
{
case (rand < 1):
gameObject.renderer.material.mainTexture = red;
break;
case 1 :
gameObject.renderer.material.mainTexture = green;
break;
case 2 :
gameObject.renderer.material.mainTexture = blue;
break;
}
help me ,If u can…
That’s really a generic programming question. And a little tricky. You have 72 colors (18 repeated four time each) randomly arranged. Could write them all in order (r,r,r,r,g,g,g,g …) then use a standard shuffle.
Do all colors on one cube have to be different? That’s harder. Might assign a “good” coloring then make 1000 legal random switches. Or look at some combinatorics sites (the technical word for arranging items with various rules.)
Or, and this common when anyone runs into something which is a lot more difficult than it looked, you might decide that having 5 of one and 3 of another is just fine.
The “shuffle” method @owen-reynolds suggested is good advice. See also here under “Shuffling a List”.
If you’d like to extend your approach instead, you could use a brute force search like this:
// initialize somewhere above
var amountPerColor : int[] = new int[3];
amountPerColor[0]=4; // 4 red
amountPerColor[1]=4; // 4 green
amountPerColor[2]=4; // 4 blue
...
// where you create a new object/texture
// safety net: don't call this more often than allowed, we would run into an infinite loop!
if(amountPerColor[0]==0 && amountPerColor[1]==0 && amountPerColor[2]==0){
Debug.LogError("No more selections available!");
return;
}
var rand:int=0;
do{
rand=Random.Range(0,3);
}while(amountPerColor[rand]==0); // repeat until we found an available color
amountPerColor[rand]--; // found one, so one less available now
switch(rand){
// your switch/case segment from above goes here
}