Do some stuff when i select an object in the Outliner

Just to illustrate what i’m currently trying to achieve

https://lh5.googleusercontent.com/-OgyJkByusFo/VD_OI7vBH6I/AAAAAAAAABM/12ORGcsq1_M/w310-h332-no/python_outliner.gif

I wish to hide all objects except the one i just selected in the outliner. The code for this is quite simple, but i can’t seem to find any way to track the selection event itself. The smartest thing i came up with is just to mimic object tree with buttons in a custom panel, but i don’t really want to do that.
Any workaround would be awesome, even if it is extremly ‘slow’ or ‘hackish’ or even considered a ‘bad practice’ :eyebrowlift:.

Looks like in my particular case there is actually no need to do anything special. All my objects are just planes with images which share the same position in a 3D space. In 2.69 that looked like a mess with images randomly overlapping one another, but in 2.72 Blender is now smart enough to just show currently selected plane on top of others.

It seems that your problem is solved.
For the fun here’s one solution anyway:


import bpy


def my_handler(scene):
    active_obj = scene.objects.active # gets active object
    active_obj.hide=False # makes it visible
    for obj in scene.objects:
        if obj != active_obj: obj.hide=True # hides all other objects


bpy.app.handlers.scene_update_post.append(my_handler) # adds handler to blender

The trick is to use handlers. They are functions that run when a certain event is met (in this case at each scene update, ie: always). Check the blender api if you want to dig into this !

To remove it, run:


import bpy


for i in bpy.app.handlers.scene_update_post: # loops through handlers
    if i.__name__ == 'my_handler':
        bpy.app.handlers.scene_update_post.remove(i) # removes the handler if its name corresponds to the previously added handler

reloading the file or closing/reopening blender will also remove the handler.

The removal code only works if you added the handler once. If by accident you run the code to add the handler twice, you’ll have to run the removal code twice as well.

Happy blending/scripting !

Wow, that’s exactly what i was looking for, thank you! Actually the problem was only half-solved, because having 30+ images shown at the same time in the same space really slows down blender, so i have to hide them anyway.

Happy to have helped ! Blend happily :wink: