replace a material directly, from the main material list ?

Hi python worshippers,

I’m trying to replace a mat by another one imported from a lib rather than append it, in some case, depending on a mat name test :

if newmat.name not in Material.Get() : append
else : update the existing one.
thus to keep user links and to avoid duplicates.

but it does not work so far. the only way I’ve found is to check every object material slots and change the old mat link to the new one.
it seems material_works.py works the wame way.

what I’d like to do is something like :

def oceAppend(path,source,what) :
	
	lib = bpy.libraries.load(path+source)
	# MATS
	# import/update/rename mats from a lib
	if what=='mats' :
		matsList=[]
		for m in Material.Get() :
			matsList.append(m.name)
		for matname in lib.materials :
			print matname
			newname=source+'_'+matname
			if newname not in matsList :
				mat = lib.materials.link(matname)
				mat.name=newname
				mat.fakeUser=True
# THE CODE BELOW DOES NOT WORK
<b>			[B]else :</b> 
				print newname,'exist'
				mat = Material.Get(newname) # the mat to update with new parameters
				m = lib.materials.link(matname)
				print 'update',mat.name,newname,'with',m.name
				mat = m.__copy__() <b># does not work</b>
				mat = m <b># does not work</b>
				mat.name=newname
				mat.fakeUser=True
				m.fakeUser=False[/B]

I change the name of the imported lib because several mats will share the same name, so I add the library name in it to avoid 001, 002 etc names.
ideally it would be great that the api provide a function that would replace an existing mat by an imported one with a renaming option, to avoid huge list of mats with zero users.

thanks for your help,

littleneo

I don’t know if this’ll help…

check out my script from this thread

I found I had to assign a new material list to the objects and had to change all the face indices accordingly… it might be useful!

I’ve written exactly the script you’re talking about last week, only that was for maya not blender so not much help for you!

aha thanks :slight_smile:
your script looks really useful, I’ll keep it under my pillow…
in fact for my needs, I’ve found another way with library external links.