To get the current active object in a Blender scene, we usually use the context and its context.object (or context.active_object) property. Similarly, when working with the interface, we can access the context to get the currently active property – the value of the field in the Blender UI over which we hover the cursor or on which we clicked with the mouse. The context.property value is used for this.
Let’s look at an example of how to get the value of the currently active property from the N-panel of the Blender interface.
First, define the simplest class for printing the context.property value to the system console.
1 2 3 4 5 6 7 8 |
class TEST_OT_c_prop(bpy.types.Operator): bl_idname = 'test.c_prop' bl_label = 'Context Property' bl_options = {'REGISTER'} def execute(self, context): print(context.property) return {'FINISHED'} |
In the “execute” function, we write the output to the console of the context.property value.
Don’t forget to register it in the Blender Python API.
1 |
bpy.utils.register_class(TEST_OT_c_prop) |
When executing the operator, the current context will be used – the context of the UI element on which the user performs the current action. Let’s say, for example, this is a call to the context menu – which opens when the user right-clicks.
Add a new item to the context menu, clicking on which will call our operator. To do this, define the “extend_menu” function.
1 2 3 |
def extend_menu(self, context): self.layout.separator() self.layout.operator('test.c_prop') |
And add its call to the UI_MT_button_context_menu handler:
1 |
bpy.types.UI_MT_button_context_menu.append(extend_menu) |
Now, when we right-click on any property field in the N-panel, a new item “Context Property” will be displayed in the menu.
When we select this menu item, our operator will be executed.
Right-click on the Location – X property and select our new item “Context Property” from the menu that opens. The following tuple will be displayed in the system console:
1 |
(bpy.data.objects['Suzanne'], 'location', 0) |
The first element of the tuple will always be a reference to the data-block to which this property belongs.
On the second place will be the name of this property.
And on the third – the ordinal index of the element, if the property is of array type.
Expand the data output of our operator a little by adding a few more lines to the “execute” function:
1 2 3 4 5 6 7 8 9 |
def execute(self, context): print(context.property) print(getattr(context.property[0], context.property[1])) if context.property[2] != -1: print(getattr(context.property[0], context.property[1])[context.property[2]]) return {'FINISHED'} |
Here we additionally receive the actual data of the active property and, if it is of array type, specifically the value of the current element.
Our console output now looks like this:
1 2 3 |
(bpy.data.objects['Suzanne'], 'location', 0) <Vector (0.8600, 1.3400, 1.4600)> 0.85999995470047 |