3
$\begingroup$

Although my script works as it should I'm experiencing a odd behaviour when I run it, all the objects get selected and I have no idea why this is happening.

import bpy
import os
import subprocess
import math
from bpy.props import (
    FloatProperty,
    StringProperty,
)
from bpy_extras.io_utils import ImportHelper
from mathutils import Matrix, Vector
from bpy.types import (
    Header,
    Menu,
    Panel,
)
from math import isclose


class SelectByNameOperator(bpy.types.Operator):
    """Description"""
    bl_idname = "object.selected_by_name_operator"
    bl_label = "Select objects by name"
    bl_options = {'REGISTER', 'UNDO'}

    name = StringProperty(
            name="Object name",
            )

    def execute(self, context):
        for obj in bpy.context.scene.objects:
            if obj.name.startswith(self.name):
                obj.select_set(True)
                bpy.context.view_layer.objects.active = obj
            else: 
                obj.select_set(False)

                
                
        return {'FINISHED'}                 


class MyPanel(Panel):
    """Creates a Panel in the Object properties window"""
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'UI'
    bl_category = "Test"
    bl_label = "Test"
    bl_idname = "MyPanel"
    
    
    def draw(self, context):
        layout = self.layout
    
        box = layout.box()
        row = box.column()
        row.operator("object.selected_by_name_operator")

    
def register():
    bpy.utils.register_class(MyPanel)
    bpy.utils.register_class(SelectByNameOperator)
    
def unregister():
    bpy.utils.unregister_class(MyPanel)
    bpy.utils.unregister_class(SelectByNameOperator)
    
    
if __name__ == "__main__":
    register()
$\endgroup$

1 Answer 1

5
$\begingroup$

All strings "start with nothing".

Simple test in python console

>>> x = "xxx"
>>> x.startswith("")
True

Similarly with your operator since the default value when not set of a string property is "".

Either test for this, or give it some default.

Note, there is already a similar op, to select all objects that start with "Cube"

>>> bpy.ops.object.select_pattern(pattern="Cube*")
{'FINISHED'}
$\endgroup$
0

You must log in to answer this question.

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