11
$\begingroup$

i have trouble to get a script working within Blender 2.8. The following function work perfectly for me in Blender 2.79, but not in 2.8.

def CreateMaterialFromImage(matName, imgPath):
    '''Creates and returns a material from an Image'''
    realpath = os.path.expanduser(imgPath)
    try:
        img = bpy.data.images.load(realpath)
    except:
        raise NameError("Cannot load image %s" % realpath)

    # Create image texture from image
    cTex = bpy.data.textures.new(matName, type='IMAGE')
    cTex.image = img

    # Create material
    mat = bpy.data.materials.new(matName)

    # Add texture slot for color texture
    mtex = mat.texture_slots.add()
    mtex.texture = cTex
    mtex.texture_coords = 'UV'
    mtex.use_map_color_diffuse = True
    mtex.use_map_color_emission = True
    mtex.emission_color_factor = 0.5
    mtex.use_map_density = True
    mtex.mapping = 'FLAT'
    return mat

It seems to be that the material.texture_slots were removed.

Under following Link https://lists.blender.org/pipermail/bf-blender-cvs/2018-April/106620.html i found the note:

  • Texture slots for materials, lamps and world were removed. They remain for brushes, particles and freestyle linestyles.

So my question is where do i find this property now or how could i change my code to get things done?

Thanks for your help!

EDIT: https://en.blender.org/index.php/Dev:2.8/Source/Python/UpdatingScripts This seems to be an interesting link for people run in to issues by updating their scripts to 2.8. Unfortunately there is no solution for my problem listed, yet.

$\endgroup$
1
  • $\begingroup$ A little correction: It should be ValueError instead of NameError, name error is for variable not found by name. eg. didn't assign it before access the variable. $\endgroup$
    – HikariTW
    Jul 26, 2020 at 1:23

1 Answer 1

15
$\begingroup$

I've been able to do this in blender 2.80 as follows:

mat = bpy.data.materials.new(name=name)
mat.use_nodes = True
bsdf = mat.node_tree.nodes["Principled BSDF"]
texImage = mat.node_tree.nodes.new('ShaderNodeTexImage')
texImage.image = bpy.data.images.load("C:\\path\\to\\im.jpg")
mat.node_tree.links.new(bsdf.inputs['Base Color'], texImage.outputs['Color'])

# Assign it to object
if ob.data.materials:
    ob.data.materials[0] = mat
else:
    ob.data.materials.append(mat)
$\endgroup$
1
  • $\begingroup$ I tried this and the texture worked, but it does not show up under properties Texture button. Is there any way to get it added to that? $\endgroup$
    – Invariant
    Aug 14, 2019 at 1:59

You must log in to answer this question.

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