I'm struggling with how can I create a random color between some range.

To explain better I have this: Cube Node
But I want these each cube has one random color.
My code:

shader RandChecker4(

    point Pos = P,
    float Scale = 1,
    float Rand = 0,
    color Color1 = color(1,0,0),
    color Color2 = color(0,1,0),
    color Color3 = color(0,0,1),
    color Color4 = color(0,1,1),

    output color Col = 0


    point p = Pos * Scale;
    int x = (int)mod(p[0],2.0);
    int y = (int)mod(p[1],2.0);
    int z = (int)mod(p[2],2.0);

    color Colorlist[4] = {Color1,Color2,Color3,Color4};
    int r = (int)mod(Rand*10,4.0);

    if(x%2==1 && y%2==1 && z%2==1){
        Col = Colorlist[r];


In order to have each 'square' to be a consistent color you need to change the coordinates fed into the Noise texture to change in discrete steps. This can be achieved using a Modulo function. The Modulo node effectively divides the input value by the specified amount and outputs the remainder. By subtracting the remainder we can produce a 'stepped' value. Since this value does not change over the specified range (in this case 1/7 - to match the scale of the 'squares' texture of 7) the result of the Noise will be constant over that range, resulting in a constant color.


Note that I also added a Mapping node to offset the coordinates slightly - so that the squares correspond to all faces.

  • $\begingroup$ woowh.. this is so cool. Thank very much! $\endgroup$ – Yugo Harago May 18 '18 at 16:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.