2 of 3
deleted 18 characters in body
  • 15.9k
  • 10
  • 83
  • 143

Operators like bpy.ops.import_scene.obj() can't return the object name itself. If you know the name of the imported object(s) simply use this: bpy.data.objects['yourname'] and assign it to a variable to apply a material on it:

# assignment
obj = bpy.data.objects['yourname']
# append material

If you don't know the name of the the imported object(s) you have to select them after the import with something like this:

# single selection
obj_object = bpy.context.object
# multiple selection
obj_objects = bpy.context.selected_objects[:]

Here is a working example for importing multiple objects from 1 obj file. It appends a newly created material on the imported objects and prints out their names for error handling.

import bpy

full_path_to_file = "test.obj"

# make sure to get all imported objects
obj_objects = bpy.context.selected_objects[:]

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

# iterate through all objects
for obj in obj_objects:
    # print the name of the current obj
    print (obj.name)
    # set current object to the active one
    bpy.context.scene.objects.active = obj

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

    # if a material exists overwrite it
    if len(obj.data.materials):
        # assign to 1st material slot
        obj.data.materials[0] = mat
    # if there is no material append it
    # move the object, if it's named "Cube"
    if (obj.name == "Cube"):
        obj.location = (0,0,10)
  • 15.9k
  • 10
  • 83
  • 143