ItemList has a function to Get_Item_Count to see how many items are in an ItemList. Is there something silimar to that in a Tree node? Or do I have to Get_Children() and the count how many are returned?
How to get the count of TreeItems in a Tree?
I usually use get_child_count()
- Edited
I have tried that. It sounds reasonable, but it doesn't return a correct number. I clean fresh created Tree always returns 6 with get_child_count(). Even after adding TreeItems, it returns 6. Perhaps get_child_count() is returning the internal node count of the nodes that make up the Tree, not the TreeItems?
A tree should only have a single root, so I think you can do something like this to get the number of children in a TreeItem like the root:
var tree = get_node("Tree")
var treeRoot = tree.get_root()
var treeRootCount = 0
var treeRootChild = treeRoot.get_next()
while (treeRootChild != null):
treeRootCount += 1
treeRootChild = treeRootChild.get_next()
print ("There are ", treeRootCount, " children in the tree root")
Thank you Twisted. Wish there was an easier way as the Tree node is full of great potential. I did have to make one adjustment to your code. line 5 didn't work for me. I had to use treeRoot.get_children()
which is poorly named as it only returns the FIRST TreeItem of treeRoot and not all the children as the name implies.
- Edited
Could it be that you are expecting Node class' get_children()
to return the whole tree but it really returns an array of (edit: references to) only the direct children?
- Edited
I've never used a Tree before, but I imagine a while loop that calls get_children() recursively would work.
Yep, get_children() is only the first direct child and get_next() finds siblings, not grandchildren.
A recursive count function:
func recursiveCount(item):
if item==null:
return 0
var count = 1
var child = item.get_children()
while child!=null:
count += recursiveCount(child)
child = child.get_next()
return count
Call that on your root node and it will count every tree item (including the root).
print(recursiveCount(tree.get_root()))
A lot of work for a treeItem count. There should just be an internal int that ++ every time you add a TreeItem and -- every time you delete.
Yeah, the get_children
function only returns the first child directly under the TreeItem it's called on, which is not very intuitive. The Tree node probably could use a refactoring to change the names a little, but I think it's been left the way it is for compatibility with old code.
@Kojack said: Yep, get_children() is only the first direct child and get_next() finds siblings, not grandchildren.
A recursive count function:
func recursiveCount(item): if item==null: return 0 var count = 1 var child = item.get_children() while child!=null: count += recursiveCount(child) child = child.get_next() return count
Call that on your root node and it will count every tree item (including the root).
print(recursiveCount(tree.get_root()))
Awesome, thanks for sharing!