2
$\begingroup$

I am trying to take all the selected objects and rename them based on their active material. I can make it work with the active object, but I can't figure out a way to do it with the selected objects.

This is what I have for the active object, that works as expected.


import bpy

#takes active object and renames it to the active material
name = bpy.context.active_object.active_material.name
bpy.context.object.name = name

Thanks in advance!

$\endgroup$

1 Answer 1

2
$\begingroup$

You can do something like this:

import bpy

for ob in bpy.data.objects:
    if ob.select_get():
        #ob.name=ob.material_slots[0].name #this can fail if no material is assigned
        print(ob.name)

Or using context as @batFINGER suggests

import bpy

for ob in bpy.context.selected_objects:
     #ob.name=ob.material_slots[0].name #this can fail if no material is assigned
     print(ob.name)
$\endgroup$
3
  • $\begingroup$ Thank you, that was a quick response and it works exactly as I hoped! Where is the best place to learn the for/if statements? and like, how do you know what "o" is? $\endgroup$ Sep 3, 2020 at 22:36
  • $\begingroup$ bpy.data.objects is an iterable array, which means you can use a for statement to iterate over all of the values in the array. I called the variable "o", "ob" and "obj" are more common in example scripts, but its arbitrary. Each iteration of the for loop o points to one of the bpy.data.objects[] in the scene. $\endgroup$
    – Ron Jensen
    Sep 3, 2020 at 22:50
  • 1
    $\begingroup$ Suggest working from context and using for o in context.selected_objects: is the current scene current selection. As above will find all objects in blend file that are selected, whether in current scene, another scene or no scene. @AlexPearce the number of teach yourself python links are too numerous. $\endgroup$
    – batFINGER
    Sep 3, 2020 at 22:53

You must log in to answer this question.

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