4
$\begingroup$

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)

$\endgroup$
2
  • 1
    $\begingroup$ Perhaps there is no active object? $\endgroup$
    – Greg Zaal
    Commented Feb 2, 2015 at 13:40
  • $\begingroup$ 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 $\endgroup$
    – Ross
    Commented Feb 2, 2015 at 13:42

1 Answer 1

6
$\begingroup$

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
$\endgroup$
3
  • $\begingroup$ 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? ) $\endgroup$
    – Ross
    Commented Feb 2, 2015 at 15:27
  • $\begingroup$ @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. $\endgroup$
    – sambler
    Commented Feb 3, 2015 at 0:48
  • $\begingroup$ @sambler yeah. The material was already assigned. I used obj.data.materials[0] to give my texture. Thank you :) $\endgroup$
    – Ross
    Commented Feb 3, 2015 at 6:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .