Don't recommend addressing by name.
Using name as a sole variable to lookup objects in blender is fraught with danger.
If you really do only want to test for the original, and named "Cube" cube object there are two conditions to look at
cube_in_blend = bpy.data.objects.get("Cube") is not None
cube_in_scene = context.scene.objects.get("Cube") is not None
If cube not in blend then
if not cube_in_blend:
bpy.ops.mesh.primitive_cube_add()
cube = context.object
will result in both being true. If the cube is in file and not in scene
if cube_in_blend and not cube_in_scene:
cube = bpy.data.objects.get("Cube")
context.scene.objects.link(cube)
links the object named "Cube" to that scene. There is no guarantee that it has 8 equal length edges, 4 equal area faces and other props expected of a cube.
Alternatively
Just like a scene has a camera, context.scene.camera
can set it up to "have a cube"
bpy.types.Scene.cube = bpy.props.PointerProperty(type=bpy.types.Object)
And in scene with cube can be set via
scene.cube = scene.objects.get("Cube")
Using method outlined in answer to Limit "prop_search" to Specific Types of Objects and modified to associate a particular cube with a scene. The cube is chosen from file objects that have a name beginning with "Cube". The cube is linked to the scene if not already. For the case where there is no cube in the scene could add the add primitive operator in the markup.
import bpy
class OBJECT_PT_HelloWorldPanel(bpy.types.Panel):
"""Creates a Panel in the Object properties window"""
bl_label = "Hello World Panel"
bl_idname = "OBJECT_PT_hello"
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "object"
def draw(self, context):
layout = self.layout
scene = context.scene
layout.prop(scene, "cube")
def scene_mychosenobject_poll(self, object):
return object.name.startswith("Cube")
def link_to_scene(self, context):
if self.cube and self.cube.name not in self.objects:
self.objects.link(self.cube)
def register():
bpy.utils.register_module(__name__)
bpy.types.Scene.cube = bpy.props.PointerProperty(
type=bpy.types.Object,
poll=scene_mychosenobject_poll,
update=link_to_scene
)
def unregister():
bpy.utils.unregister_module(__name__)
del bpy.types.Scene.cube
if __name__ == "__main__":
register()
bpy.data.objects
. If you want to check whether an object with the name 'Cube' exists, you would have the conditionbpy.data.objects.get('Cube') != None
$\endgroup$