recursive functions

BradCarstenBradCarsten Posts: 856

Question 1: I'm trying to create a recursive function that will start at a parent node and work its way through the children, printing out their assetId, but it only returns the first child in each instance. 

function GetChildren(oNode){	ChildrenNode=oNode.getNodeChildren();	if (ChildrenNode!=null) {		for ( i = 0; i < ChildrenNode.length; i++ ) {			print("num "+i+" Length"+ChildrenNode.length+' Parent: '+oNode.assetId+' Child: '+ChildrenNode[i].assetId);			GetChildren(ChildrenNode[i]);				}	}} GetChildren(Scene.getPrimarySelection());

If I start with the following parent child structure: 

Square

-childSquare1

--Grandchild1

--Grandchild2

-childSquare2

It will only return (-childSquare1, --Grandchild1 )

Any idea what I'm doing wrong? 

Question 2: how do I also return the node's label name, and not just its assetId name? *Edit* I figured this one out- have to use .getLabel().

Post edited by BradCarsten on

Comments

  • jag11jag11 Posts: 885

    Your reasoning was right, but the lack of "var" confuses the scripting engine. To avoid this pitfall always declare variables first, immediatly after the '{' character.

    var INDENT = "                 "function GetChildren(oNode, level){	if(oNode == null)		return;			var ChildrenNode = oNode.getNodeChildren();	if (ChildrenNode!=null) {		for (var i = 0; i < ChildrenNode.length; i++ ) {			var indent = (level > 0) ? INDENT.substr(1, level) : "";			print(indent + "num "+i+" Length"+ChildrenNode.length+' Parent: '+oNode.assetId+' Child: '+ChildrenNode[i].assetId);			GetChildren(ChildrenNode[i], level + 1);				}	}} GetChildren(Scene.getPrimarySelection(), 0);
  • aaah, that works perfectly. Thanks so much jag11. you wont believe how long I sat on that. 

Sign In or Register to comment.