Apply Script on spawned objects

Hi,
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

That depends on how you are spawning the cubes. If you are using an operator to do it, then after the add completes, the new cube will be the active object. You can immediately change the color of the active object.

If you are adding it though regular python, then the add function should return a reference to the new object and you would want to operate on that.

Hmm ok that makes sense. Do you have an example on how to operate on the new object if I spawn it with pyhon?

I just noticed that with logic bricks also only the first cube gets a random color, all others who follow don’t…? Or did I understand you wrong?

Just fund out that when I work with “script” mode instead of “module” mode it works with random color for every cube that follows up.

However, can anyone make a example for spawning an object with python and then changing the color immediately?

Just to be clear, this work differently if you are doing it in the game engine or if you are doing it in “normal Blender”. So do you want an example for the BGE?