[Closed] Apply material based on object name
Can anyone help me get started on this? I basically want to assign pre-made materials that are in material editor slots to objects in the scene that have the same name that corresponds to the material. It seems like it would be easy but just not sure how to go about it…comparing the names and all…
Appreciate any help!!!
How about this for a start?
(
for o in objects do
(
for m in meditmaterials do
if m.name == o.name do o.material = m
)
)
or an alternative approach:
(
for o in objects where (m = meditmaterials[o.name]) != undefined do
o.material = m
)
Depending on what input you expect you might want to do different optimizations of course. For example only loop through geometry instead of all objects.
(
local mEditorNames = for i = 1 to 24 collect meditMaterials[i].name
for o in objects where (local ind = findItem mEditorNames o.name) > 0 do
(
o.material = meditMaterials[ind]
)
)
I was curious about the performance of these 3 alternatives, so I did a quick benchmark:
Output for 1000 iterations:
Method A: Time: 18.611 Seconds, Memory: 3637.57 KB, Time per iteration: 18.611ms
Method B: Time: 8.57 Seconds, Memory: 2333.09 KB, Time per iteration: 8.57ms
Method C: Time: 8.679 Seconds, Memory: 3923.6 KB, Time per iteration: 8.679ms
Where A, B and C are the different approaches in order of this thread. With 100 objects, half of which would match their name with a material editor slot. You can almost certainly make a faster function, but this gives some idea.
here is mine:
fn method_D =
(
for mat in meditmaterials do
(
if (nodes = getnodebyname mat.name all:on).count > 0 do nodes.mat = mat
)
)
1000 nodes and 100 iterations:
B: time:1168 memory:6570432
C: time:1100 memory:6733528
D: time:786 memory:726232
Hehe, nice isn’t it I use it quite a lot and I find it very useful. So nice work on that!
Oh that’s some interesting results! I had not thought the getnodebyname function would even be close to that fast. Also nice to know that setting properties is mapped.
my function is faster because I’m going through shorter loop (using materials instead of nodes). The getnodebyname itself is not a fast function.
I just thought of something as i was looking at Method C. All these approaches are limited to the number of material(24) slots right?
Yes. Although in the other methods the number of materials is implicit. The loop “for m in meditmaterials” operates on all materials in that collection which represents the material editor slots. At the moment that number is always 24.
Still the getNodeByName has to inspect all nodes. But I suppose that because this is implemented in the SDK it’s much faster.