1
$\begingroup$

The Blender documentation explains how to apply multiple materials to various selections in Text:


(source: blender.org)

For example, to create Fig. Red Green Blue. you would need to create three separate materials and three separate material indices. Each word would be assigned a Material index by selecting the characters for each word and clicking the Assign button. Fig. Red Green Blue. is still one single Text object.

When accessing the text using a Python script, we can see its contents as a string through the following command:

object.data.body

However, it is not clear to me how we could mark substrings and assign materials to them. Do we need to macro the operations (select a range, assign material, repeat) as if we were doing this through the UI? Is there a more streamlined API?

Is this achievable through a script at all?

$\endgroup$

1 Answer 1

2
$\begingroup$

The following script will cycle through all text objects and for each word (separated by space) assign a material slot index to the word incrementing the material slot through all available slots resetting to index 0 if there are more words than material slots. Written & tested on blender 2.79

import bpy

texts = [obj for obj in bpy.data.objects if obj.type == 'FONT']

bpy.ops.mode_select
for txt in texts:
    me = txt.data.body
    mats = txt.material_slots
    ind = 0
    bpy.ops.object.mode_set(mode='EDIT')
    bpy.ops.font.move(type='LINE_BEGIN')
    for word in me.split():
        bpy.ops.font.move_select(type='NEXT_WORD')
        bpy.context.object.active_material_index = ind
        bpy.ops.object.material_slot_assign()
        if ind < len(mats):
            ind += 1
        else:
            ind = 0
        bpy.ops.font.move(type='NEXT_CHARACTER')
    bpy.ops.object.mode_set(mode='OBJECT')
$\endgroup$
1
  • $\begingroup$ This code gives me this error on UPBGE 0.3: RuntimeError: Operator bpy.ops.font.move.poll() failed, context is incorrect $\endgroup$ Jun 9, 2022 at 9:30

You must log in to answer this question.

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