So, I would like to edit my previous python snippet, because I discovered something that didn’t make it work particularly well which I will try to explain and show you how to fix it. Thanks to Rick for telling me how to make it work properly, and then telling me again after I forgot to save the code somewhere.

picture-6

This is my hierarchy. Now, our script was supposed to just go down our selected object’s hierarchy. Which at first glance it does. But, it doesn’t quite work. If you select object named 2(not 2A) and run the script, it prints from 2-16. But it shouldn’t since 10-16  are are not actually children of 2, they are siblings. I want to run through a hierarchy of a selected object. This becomes more apparent when you select 1, and see as it prints 1-16, AND ABC. Whaaaat!? So, my fault, I should have tested it better. Actually, I did. I tested it thoroughly which is how I found the problem ;) . I should have waited to write about it.

Anyway, so the solution was presented to me by Rick, so thanks for that. The fix is easy.

def GoDownHierarchy(obj):
if obj is None: return

#Actions can go here
print (obj.GetName())
#End Actions
if (obj.GetDown()):
GoDownHierarchy(obj.GetDown())
if (obj.GetNext()):
GoDownHierarchy(obj.GetNext())

That’s our Code where we left off. We just need to adjust it a little bit. First, in order for this to work, we need to specify where we want this to stop. So we need to pass a second argument that mentions where we want to stop. So our first line will be changed to:

def GoDownHierarchy(obj, stop):

So now we need to check to see if we’ve reached the stop point. So we need a little check in there after our initial “if obj is None” check:

...
if obj is None: return
if obj==stop: return
...

Now, the last thing we need to, is update our function elsewhere in the code. Remember we do two more checks(if statements) and they run the function again, so since we need two arguments, we need to put in the stop argument in both.

So the whole Code for the function is now:

def GoDownHierarchy(obj, stop):
if obj is None: return
if obj==stop: return
#Actions can go here
print (obj.GetName())
#End Actions
if (obj.GetDown()):
GoDownHierarchy(obj.GetDown(), stop)
if (obj.GetNext()):
GoDownHierarchy(obj.GetNext(), stop)

So if you want to run this on the selected object’s hierarchy you would type:


GoDownHierarchy(op, op.GetNext())

So with that code, if I select object 2 in my hierarchy and run it, it goes from 2-9. Since 10 and onward is not a child of 2, it does not get printed.

Enjoy.

Leave a Reply