Python vs GUI performance for assigning Material to object

[I]Hi all,
I’ve run into a serious performance issue when using Python that I wasn’t able to find an answer to using a search.
I’m trying to render a series of frames, where for each frame different stl files are read. After loading the stl files I would like to assign the resulting mesh objects a predefined material. Here’s the code segment that loops through all scene objects and assigns to those that start with Mesh the material water.

	sce = Blender.Scene.GetCurrent()
	# assign water material to loaded stl meshes
	for obj in sce.objects:
		if obj.type == 'Mesh':
			objname = obj.getName()
			iid = objname.find("Mesh")
			if iid == 0:
				print objname
				print 'GetData'
				n = obj.getData()
				print 'Assign material'
				n.materials = [water]
				print 'update'

	print 'Done updating materials'

Here’s the problem:
The last command n.update that updates the materials object takes extremely long (as timed by the print commands). It takes at times several hours per object (granted, the binary stl files are about 25MB (2 total)). If I do the same action through the GUI (select the mesh, assign the material), this takes only a second.

Is there a other/faster way of assigning a material to a mesh object in Python than the one I used above?

Thanks in advance!


I’m not certain, but I think the problem is that you’re not assigning a material to the mesh (perhaps you’re trying to assign a string “water”). You first have to get the water material data, before you can assign it.
But why are you even using mesh.update? As far as I know it isn’t needed. The following works fine for me:

import bpy
from Blender import Window

water =['water']

for me in
    me.materials = [water]


This will set the material of all meshes to the water material. Obviously you can do some filtering by mesh name or any other thing you can come up with, but this is the basic idea. On my pretty weak computer this takes in the range of milliseconds even if the scene contains over 5 million vertices.
If you really need the update function you can add me.update() below the me.materials=[water] line and it should still take less than a second.

sorry, I left out the initial parts of the script where I get the water material:

water = Blender.Material.Get("Woda")

When I skip the me.update() command, the materials don’t get assigned, so I think I have to have it in there. However, I noticed you are using the bpy module, whereas I was using the Blender module, so maybe that’s the reason why you are so much faster than what I’m seeing? I’ll try to convert my script to bpy and see what will happen.

Thanks again,

just an update: the switch to the bpy module solved my issue. Thanks Crouch!