1

I'm trying to script something in blender3D using python. I've got a bunch of objects in my scene and want to translate them using a the numerical part of their objectname.

First of all i collect objects from the scene by matching a part of their name.

root_obj = [obj for obj in scene.objects if fnmatch.fnmatchcase(obj.name, "*_Root")]

This gives me a list with:[bpy.data.objects['01_Root'],bpy.data.objects['02_Root'],bpy.data.objects['03_Root'],bpy.data.objects['00_Root']]

My goal is to move these objects 15x their corresponding part of the name. So '00_Root' doesnt have to move, but '01_Root' has to move 15 blender units and '02_Root' 30 blender units.

How do i exctract the numberpart of the names and use them as translation values.

I'm a pretty newb with python so i would appreciate all the help i can get.

1 Answers1

0

A string is a list of characters, each character can be accessed by index starting with 0, get the first character with name[0], the second with name[1]. As with any list you can use slicing to get a portion of the list. If the value is always the first two characters you can get the value with name[:2] you can them turn that into an integer with int() or a float with float(). Combined that becomes,

val = int(name[:2])

You then have a number you can calculate the new location with.

obj.location.x = val * 15

If the number of digits in the name might vary you can use split() to break the string on a specific separating character. This returns a list of items between the specified character, so if you want the first item to turn into an integer.

name = '02_item'
val = int(name.split('_')[0])

Using split also allows multiple values in a name.

name = '2_12_item'
val1 = int(name.split('_')[0])
val2 = int(name.split('_')[1])
Community
  • 1
  • 1
sambler
  • 6,917
  • 1
  • 16
  • 23