How do I delete texture slots?

Hovering over the minus sign in the materials panel gives you a nice little:

bpy.ops.object.material_slot_remove()

to remove material slots in your code. But I’ve found no simple solution for deleting texture slots. What’s the best way to delete a texture slot and the texture along with it via script (referring to Blender internal render type textures, but any information welcome)?

If you take a look at the API you will see there is no remove() method for texture slots. You can add() and clear() them however.
http://www.blender.org/documentation/blender_python_api_2_70_5/bpy.types.MaterialTextureSlots.html?highlight=texture_slots

So to delete a slot you need to make a list with all the names in the current texture slots and then clear the texture slots. Then go back through the list and add the textures back in except for the one you wanted to remove.

I’m familiar with that page, I was staring at it for 30 minutes trying to figure out how to make it delete a texture slot.

So to delete a slot you need to make a list with all the names in the current texture slots and then clear the texture slots. Then go back through the list and add the textures back in except for the one you wanted to remove.

Maybe just set the texture to None?

mat = bpy.context.object.data.materials['Material']
ts = mat.texture_slots[0] # first texture slot
if ts is not None:
    ts.texture = None

Thanks CoDEmanX and Atom. That worked. Only now, blank texture slots still remain between textures. Any idea how I might rid the index of those blank slots? I know there’s a bunch of blank slots by default, I mean the slots that would be in between texture slots that are being occupied. Basicly, smush them all next to one another.

I think Atom’s method of clearing the list would probably do it, but every time I attempt to use the clear() method it crashes Blender or I get an error about how the index is incorrect. I’m not really sure how to implement getting rid of them. Thanks for any help.

I have some code that has to clear and rebuild texture slots based on shaders used. UV layers are also involved with these textures. The texture slot removal code follows:


    for c in range(18):
        if DestMaterial.texture_slots[c] != None:
            DestMaterial.texture_slots.clear(c)
            bpy.ops.mesh.uv_texture_remove()
    DestMesh.update()

How about this:

import bpy

try:
    ob = bpy.context.object
    mat = ob.active_material
    tex = mat.active_texture
    ts_index = mat.active_texture_index
except AttributeError:
    print("Need object with active material and texture!")
else:
    mat.texture_slots.clear(ts_index)
    try:
        bpy.data.textures.remove(tex)
    except (RuntimeError, TypeError): # catch exception if there are remaining texture users or texture is None
        pass

It uses the active material and texture, removes the texture slot and also the associated texture if there’s no other user.