PashavanBijlert / MuSkeMo

Build and visualize musculoskeletal models in Blender
2 stars 0 forks source link

Update objects based on selection state #44

Open PashavanBijlert opened 2 months ago

PashavanBijlert commented 2 months ago

E.g., if one body is selected - update the body name body property. Sample code:

import bpy

Custom property group to hold the string property

class ObjectNamePanelProps(bpy.types.PropertyGroup): object_name: bpy.props.StringProperty(name="Selected Object Name")

Panel class to display the property

class OBJECT_PT_DynamicNamePanel(bpy.types.Panel): bl_label = "Dynamic Object Name Panel" bl_idname = "OBJECT_PT_dynamic_name_panel" bl_space_type = 'VIEW_3D' bl_region_type = 'UI' bl_category = 'My Panel'

def draw(self, context):
    layout = self.layout
    scene = context.scene
    props = scene.dynamic_name_panel_props

    # Show the current object name or message in the panel
    layout.prop(props, "object_name")

Operator to update the string property based on selected mesh objects

class OBJECT_OT_UpdateStringProperty(bpy.types.Operator): bl_idname = "wm.update_string_property" bl_label = "Update String Property"

def execute(self, context):
    scene = context.scene
    props = scene.dynamic_name_panel_props

    # Get all selected objects of type 'MESH'
    mesh_objects = [obj for obj in context.selected_objects if obj.type == 'MESH']

    # Update the string property based on the number of selected mesh objects
    if len(mesh_objects) == 1:
        props.object_name = mesh_objects[0].name
    elif len(mesh_objects) > 1:
        props.object_name = "Multiple mesh objects selected"
    else:
        props.object_name = "No mesh object selected"

    return {'FINISHED'}

Automatically update when the selection changes

def update_string_on_selection(scene, context): bpy.ops.wm.update_string_property()

Register classes and properties

def register(): bpy.utils.register_class(ObjectNamePanelProps) bpy.utils.register_class(OBJECT_PT_DynamicNamePanel) bpy.utils.register_class(OBJECT_OT_UpdateStringProperty)

bpy.types.Scene.dynamic_name_panel_props = bpy.props.PointerProperty(type=ObjectNamePanelProps)

# Add a handler to trigger on selection change
bpy.app.handlers.depsgraph_update_post.append(update_string_on_selection)

def unregister(): bpy.utils.unregister_class(ObjectNamePanelProps) bpy.utils.unregister_class(OBJECT_PT_DynamicNamePanel) bpy.utils.unregister_class(OBJECT_OT_UpdateStringProperty)

del bpy.types.Scene.dynamic_name_panel_props

# Remove the handler
bpy.app.handlers.depsgraph_update_post.remove(update_string_on_selection)

if name == "main": register()