4

I am new to blender and having problem with import

I created 4 cubes and exported them into a .obj file. Then I import the obj file and added texture to one of the cube

import bpy
full_path_to_file = "C:\\Users\\xyz\\Documents\\test.obj"
bpy.ops.import_scene.obj(filepath=full_path_to_file)
object = bpy.data.objects['cube1_Cube_Cube.005']
object.select = True
selectedObject = bpy.context.selected_objects
mat = bpy.data.materials.new('pixelColor')
mat.diffuse_color = (1.0,0.0,1.0)
mat.diffuse_shader = 'LAMBERT'
mat.diffuse_intensity = 1.0
bpy.context.object.data.materials.append(mat)

But this shows error in the last line:

AttributeError: 'NoneType' object has no attribute 'data'

This error does not occur if I create the object in the file itself(that is if I don't import)

p2or
  • 15,860
  • 10
  • 83
  • 143
Ross
  • 257
  • 1
  • 3
  • 7
  • 1
    Perhaps there is no active object? – Greg Zaal Feb 02 '15 at 13:40
  • I don't select any obj. I just get the cubes from the import and directly apply texture to the cube specified by its name. I get the cubes in the scene but the error occurs while applying texture – Ross Feb 02 '15 at 13:42

1 Answers1

6

In the example given, you're expecting an active object, (bpy.context.object) when there are none.

Its possible to have selected objects, but nothing active.

In this case you don't even need to have an active object. You can assign the material directly to the object, there is no need to selecting it before:

# create the material
mat = bpy.data.materials.new('MaterialName')
mat.diffuse_color = (1.0,0.0,1.0)
mat.diffuse_shader = 'LAMBERT'
mat.diffuse_intensity = 1.0

# get the object
obj = bpy.data.objects['Cube']

# get the material
mat = bpy.data.materials['MaterialName']

# assign material to object
obj.data.materials.append(mat)

# or overwrite an existing material slot via index operator
obj.data.materials[0] = mat
p2or
  • 15,860
  • 10
  • 83
  • 143
  • the problem I am having is that the textures are not showing on the imported objects(but there is no error :). Do u know how to show textures for imported objects? ) – Ross Feb 02 '15 at 15:27
  • @Ross I expect that the imported obj has a material assigned to it, appending will add a second that isn't used as it isn't assigned to any faces. Try setting your material with obj.material_slots[0] = mat if one slot exists. – sambler Feb 03 '15 at 00:48
  • @sambler yeah. The material was already assigned. I used obj.data.materials[0] to give my texture. Thank you :) – Ross Feb 03 '15 at 06:57