4
$\begingroup$

I'm currently creating an addon for Blender and got stuck at following task: -I want to select one object with an unknown name from a group with known name -I want this object to be an object instance that can be used in the following code

I tried many different things, but none of the worked. One Idea was to list all objects of the group and than select one.

newest try:

bpy.ops.object.select_same_group(group=scene.object_group)

# select one object randomly from the actives
scene.object_group is a strong property with the group name
$\endgroup$
2
  • $\begingroup$ Can you share your code with us? :) $\endgroup$
    – p2or
    Commented Nov 27, 2014 at 16:11
  • 1
    $\begingroup$ code is added above $\endgroup$ Commented Nov 27, 2014 at 16:45

1 Answer 1

3
$\begingroup$

Get the group via bpy.data.groups, all objects of that group are accessible via a Group's objects property:

import bpy
import random

group_name = "Group"

group = bpy.data.groups.get(group_name)
assert group is not None

first_ob = group.objects[0]

random_ob = random.choice(group.objects)

If you wanna select another object from a random group the active object is in, use .users_group:

import bpy
from random import choice

scene = bpy.context.scene
ob = bpy.context.object

random_group = choice(ob.users_group)
obs = random_group.objects[:]
obs.remove(ob)

try:
    random_ob = choice(obs)
except IndexError:
    # no other object in chosen group
    pass

#bpy.ops.object.select_all(action='DESELECT')
for ob in scene.objects:
    ob.select = False
random_ob.select = True
bpy.context.scene.objects.active = random_ob
$\endgroup$
5
  • $\begingroup$ THANK YOU!!!! works perfectly You solved my problem I've worked on over 1 week. now my last part of my random array Addon is finished. I'll publish the new version on my homepage soon. $\endgroup$ Commented Nov 27, 2014 at 16:57
  • 3
    $\begingroup$ @frameworker if CoDEmanX has solved your problem you can accept his answer. $\endgroup$
    – PGmath
    Commented Nov 27, 2014 at 17:11
  • $\begingroup$ @CoDEmanX Nice one, but what if group_name is not "group"? I've already been thinking about this yesterday and ended up with this: gist.github.com/p2or/526243d1af3fd21cd74d It was hard to find out in which group the object is? Do you know an easier way? $\endgroup$
    – p2or
    Commented Nov 28, 2014 at 10:14
  • 1
    $\begingroup$ In your question you said the name of the group was known. Updated my answer to show how to select a random object from a random group the current object is in. $\endgroup$
    – CodeManX
    Commented Nov 28, 2014 at 11:03
  • $\begingroup$ @CoDEmanX Thanks for updating the answer, ob.users_group also solved my issue :) I've missed that yesterday. Thanks again! $\endgroup$
    – p2or
    Commented Nov 28, 2014 at 11:15

You must log in to answer this question.

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