6
$\begingroup$

I do some testing for further learning python.

My setup is an Empty that spawns a cube every 60 tics on a random position. Now what I want is those cubes also get a random color. This is my code for it (attached to the cube on a seperate layer)

def objColor():  

    obstacle = scene.objects ["obstacle"]

    r = random.random()
    g = random.random()
    b = random.random()

    obstacle.color = (r,g,b,True)

What happens is that the first spawned cube gets a random color, but all others that follow don't. I assume that has something to do with blender changing the name of the following cubes to obstacle.001, 002 etc.

But how can I make sure that all the following cubes also get a random color?

Thanks for any help, cheers

$\endgroup$

1 Answer 1

5
$\begingroup$

Yep, you are assigning all new random colours to the first object.

def get_random_color():
    ''' generate rgb using a list comprehension '''
    r, g, b = [random.random() for i in range(3)]
    return r, g, b, 1

then in the loop, once you create the object you get a reference to it. somethng like:

obj = bpy.ops.mesh.primitive_cube_add()
obj.color = get_random_color()

This way you will call a function to get random rgba on every new object

$\endgroup$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.