0
$\begingroup$

I found a nice tutorial https://www.youtube.com/watch?v=I6o3Dq6bkn8&list=PL8iHMWPijQzs7RqTZDcXx7mtjMMTKk5es&index=116&ab_channel=Blender

this is to randomise material according a prefix name , so you can take a several materials starting with the same prefix and apply them randomly to several meshes.

how could I apply this script if each mesh use a different prefix. if I have 2 objects and I want to randomise 1 with a prefix and randomise the second one with another prefix in the same script.

I don't know anything about python

import random
import bpy

prefix = '_'

materials = []
for mat in bpy.data.materials:
     if mat.name.startswith(prefix):
         materials.append(mat)

for obj in bpy.context.selected_objects:
     obj.active_material = random.choice(materials)

here is the python script on the youtube tutorial

If anyone has a solution , that ll be great 🙏

$\endgroup$

1 Answer 1

1
$\begingroup$

You could create a list of prefixes and use a loop to check against them all. (There are other ways but this is easy to explain.) Here's your loop modified:

import random
import bpy

prefixes = ['_', '.']

materials = []
for mat in bpy.data.materials:
    for prefix in prefixes:
         if mat.name.startswith(prefix):
             materials.append(mat)

for obj in bpy.context.selected_objects:
     obj.active_material = random.choice(materials)

You can have as many prefixes in the list on the 4th line as you'd like. You just have to make sure each one is unique.

I used a period in my example. Replace it with whatever you want for your second prefix.

$\endgroup$
3
  • $\begingroup$ Thanks! it works great with material with different prefixes to use them randomly, actually I try for exemple having materials on prefix A and materials on prefix B, to assign one object the A and the other object the B only, here it's mixing both, may be my question wasnt clear enough, sorry $\endgroup$
    – aronsarea
    Commented Dec 13, 2021 at 18:29
  • $\begingroup$ No need to apologize. Perhaps I didn't understand the question. Do you mean you want two lists, one for object A and the other for object B based on prefixes? So any material that starts '_' could be used for the first object, and any material that starts '.' could be used for the second? $\endgroup$ Commented Dec 13, 2021 at 20:40
  • $\begingroup$ exactly, to be more clear and explain the idea behind this, I want to swap some haircut , so A would be for hairstyle bottom head , and B tophead. That would use the materials with prefixes. , but I don't want to play 2 scripts for each plane just one, so it combines randomly different haircut. may be I,m getting too specific, but i think a sketch could be better than words , here is a link imgur.com/YkeIpEI $\endgroup$
    – aronsarea
    Commented Dec 14, 2021 at 0:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .