create list of all the children of an object
-
On 13/05/2017 at 05:28, xxxxxxxx wrote:
Hi,
I am stuck with something which should be quite simple and would really appreciate if someone can help me with it.
I just want to create a simple list of all the children of an object. I got the point you have to use a recursive loop and found this one (I have it on a script tag) :
def process_hierarchy(op) :
print op
op = op.GetDown()
while op:
process_hierarchy(op)
op = op.GetNext()
def main() :
process_hierarchy(op.GetObject())When I define a list and append the children it is also reset at every round... (I get a list with just one child)
Here is what is not working:
def process_hierarchy(op) :
listChildren=[]
listChildren.append(op)
op = op.GetDown()
while op:
process_hierarchy(op)
op = op.GetNext()
print listChildrenDoes anyone know how I can do this list?
Many thanks,
H. -
On 13/05/2017 at 06:08, xxxxxxxx wrote:
Two solutions.
First one using GetNext/GetDown.
Second one using GetChildrenimport c4d def getchildren_v1(op, stop_obj, data=None) : if not data: data = list() while op: data.append(op) getchildren_v1(op.GetDown(), stop_obj, data) op = op.GetNext() if op == stop_obj: return data def getchildren_v2(op, data=None) : if not data: data = list() data.append(op) children = op.GetChildren() for child in children: getchildren_v2(child, data) return data def main() : obj = doc.GetActiveObject() my_list_v1 = getchildren_v1(obj, obj.GetNext()) print my_list_v1 my_list_v2 = getchildren_v2(obj) print my_list_v2 if __name__=='__main__': main()
btw if you post code into this form try to use [ code] and [ /code]
-
On 15/05/2017 at 08:17, xxxxxxxx wrote:
Hi,
thanks, gr4ph0s
Just want to add a word of explanation, why the initial code is not working. Basically in the process_hierarchy() function, you were creating a fresh new list on every call of the function, then added one object to it and when leaving the function, this list got forgotten.
As gr4ph0s demonstrates, you need to pass one list through all the calls, successively adding to it.