MEL script to assign a new material based on that objects name


#1

Does anyone know how you would go about making a script that allows you to assign a new material to an object? Not one material assigning to a batch of objects but rather a new material for each object that has the same name as the object. I’m just sick of having to assign and rename a new material for each and every object in my scene. Thanks


#2

Hi,

I try to get my head around what you mean, or trying to archieve, could you e.g. give an example?

do you mean e.g. select an Object named Box and then the material to be applied named BoxMat, or that an Object gets created and the Matrial that gets attached automaticaly to have the new name applied… e.g. creating a Object named Box (ObjectName) and at creation time the Material automatic gets assigned as BoxMat (ObjectNameMat).

or an exiting Material on the Object to be replaced on the Object, or that the Material on the Object should have the exact same name as the Object it is assigned to?

and how would you like it to work, at creation time, or by clicking the object or something completely else?

sorry for all these question, but trying to figure out what you are asking about. :slight_smile:

Kind regards

strarup


#3

Strarup, what the hell?

Guy has pretty simple request and v straight forward question.

How to go about making a script which does 3 things:

create new material
rename material with the name of the object
assign material to the object

Working with multiple selection.

Myself, Id like to have possibility to modify the name.
Erase the first character for example. To work with Unreal 4 conventions, where objects start as SM_… and materials as M_…

It would be assigned to a hotkey or as a shelf button.


#4

here is some python code using maya.cmds, you could put it in a shelf button.

# get selection
selection = cmds.ls(selection=True)

# go through each object in selection
for node in selection:
    # define material name, shading engines usually named as "materialnameSG"
    material_name = "M_{}".format(node)  
    shading_engine = "{}SG".format(material_name)
    
    # create a lamber material, or any other kind by replae almbert with other type name below
    cmds.shadingNode("lambert", name=material_name, asShader=True)  
    cmds.sets(name=shading_engine, renderable=True, noSurfaceShader=True, empty=True)
    cmds.connectAttr("{}.outColor".format(material_name), "{}.surfaceShader".format(shading_engine), force=True)
    
    # assign it to current node
    cmds.sets(node, edit=True, forceElement=shading_engine)

#5

another way to assign a material

import maya.cmds as cmds

shader_name=‘lambert1’
selection=cmds.ls(selection=True, flatten=True)
if selection:
cmds.hyperShade(assign=shader_name)