# How to unlink material from a mesh, with python script?

Blender 2.68a, Python 3.3

I would like to unlink material from a mesh, and even after googling a hour I don't know how to do it. I only saw scripts that work in Blender 2.5x only for this.

So could someone tell me (or link info), how to do this:

with python script?

Remove the first material from the mesh.

import bpy
obj = bpy.context.object
obj.data.materials.pop(0, update_data=True)


Remove all materials.

import bpy
obj = bpy.context.object
obj.data.materials.clear()


This clears images for each face (active uv layer only)

import bpy
obj = bpy.context.object
for tf in obj.data.uv_textures.active.data:
tf.image = None


This clears images for all UV layers

import bpy
obj = bpy.context.object
for texlay in obj.data.uv_textures:
for tf in texlay.data:
tf.image = None


• Trying to avoid comments, like "thanks"... LOL but thanks, I would never thought it is the "pop" I was looking for. Will accept in 2 mins, and vote up when I get 15 repu. – Zéiksz Aug 13 '13 at 9:02
• Ideally we would be able to do: del obdata.materials[0], Which would be the most obvious way to do this, but this way doesn't accept arguments for how to handle linked data. – ideasman42 Aug 17 '13 at 12:07
• Is there something similar for textures? – McLawrence Aug 13 '18 at 15:27
• @McLawrence best ask a new question, link to this one. – ideasman42 Aug 13 '18 at 23:36

You can also do the following to properly remove materials. This will both unlink the materials and also remove the unlinked materials from memory. ideasman42's original solution does not remove the left-over data blocks and can cause memory leakage issues unless you close/re-open Blender or exit the current Python environment (themultiprocessing package can help with the latter). Here's a modified version of the solution that ideasman42 proposed that properly removes materials:

import bpy
obj = bpy.context.scene.objects.active
mats = obj.data.materials

for mat in mats:
mat.user_clear()

matLength = len(mats)
for i in range(matLength):
obj.data.materials.pop(0, update_data=True)

leftOverMatBlocks = [block for block in bpy.data.materials if block.users == 0]
for block in leftOverMatBlocks:
bpy.data.materials.remove(block)
bpy.context.scene.update()

mats.clear() # I'd recommend not executing this line. It might sometimes cause the object not be shown in final rendering