I am trying to set up a scene using Python in BGE, there may be a simple way to do it. It is easier for me to explain the problem I have with a very simple Blender session:
Start with a new Blender session, delete the default cube. Add a plane as a floor, and attach an Always sensor to it, and connect the sensor to a Python controller running the following script (3 lines only)
bpy.ops.mesh.primitive_cube_add(location=(0, 0, 5))
bpy.context.selected_objects.game.physics_type = 'RIGID_BODY'
When I press P to run in the Blender Game mode, I can't see the cube created. When I press Esc, I can see a new cube was created. When I press P again, I can see the original cube fall down and rest on the floor. When I press Esc again, I can see the original cube goes back to the original position, and another new cube was created at that same spot.
It is easy to modify the code so only one cube is created even if I run the script multiple times. I can also solve the problem easily as follows: Forget the sensor/controller, just run the script to setup the cube manually before BGE, and then play the game to see the cube falling onto the floor. But I don't like to have to run extra code to setup the scene.
What I have here is a very simple scene. My question is how to, in general, use Python to setup a scene at the start up of BGE?
Based on what I see, it seems that BGE execute the Python code at exit (when I press ESC to quit). How can I make sure the code is executed at the beginning (when I press P).