Notifications
Clear all

[Closed] Creating a material with the object name

I have managed to piece together a number of code snippets to get very close but with little knowledge I am struggling with the final part. I’m thinking it’s probably a word or two off literally.

The purpose of the script is to loop through the open file, delete any existing materials (Geometry.material = undefined) then create a new material for each given object with the same name as the object.

Example I have 5 box’s called box1,box2,box3,box4,box5. All materials are stripped. The script loops through all Geometry finds first object i.e box1 creates a new material and names that material box1. The the script continues to loop through until all objects have a corresponding material created.

I have attached where I got too. I was able to do what I wanted but only to a selected piece of geometry, but not to loop through and continue to create materials for each object.

Any help would be much appreciated.

4 Replies

Change line 6:

newmat.name = ( $.name as string)

to:

newmat.name = ( selection[i].name as string)

and you should be good. There is really no need to remove the materials first, because they will be replaced as soon as you assign a new material.

-Eric

Hi Eric,

Thanks for the quick response.

It still only seems to run the script on an individual object and not multiple objects or all objects in scene? Not quite sure how to do that?

Many thanks

1 Reply
(@pixel_monkey)
Joined: 11 months ago

Posts: 0

This will replace all geometry materials:

for i in geometry do
(
	newmat = StandardMaterial name:( i.name as string)
	i.material = newmat
)

To do it on a selection then use:

for i in selection do
(
	newmat = StandardMaterial name:( i.name as string)
	i.material = newmat
)

Since you aren’t removing items and unless you have a huge selection/geometry count then it will be slightly faster to loop through the collect as a whole instead of by index. By index has its advantages, but it slightly slower. Also, you can define the material name during material creation by setting the name: parameter at creation time.

Hope that helps,
-Eric

Thanks Eric,

Worked like a dream!

Many thanks