How to setup a simple scene using Python in BGE? 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)

import bpy

bpy.ops.mesh.primitive_cube_add(location=(0, 0, 5))
bpy.context.selected_objects[0].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).
ShungChing!

This problem is due to the fact that you are using the wrong library. When you use Blender Game Engine, you have to use bge library instead of bpy. 
Try to do the next things:
1) Add an empty in the position you wan to add cube;

2) Add the cube to another layer;

3) To Empty object attach the always sensor --> python controller --> EditObject actuator(make the actuator's name is 'AddCube')

4) The script:

import bge
from bge import logic, types

cont = logic.getCurrentController()
act = cont.actuators["AddCube"]
act.instantAddObject()


Answer files