|
To be able to add nodes to treeView in their hierarchy we will need a recursive function. I expect that
any one that is starting to work with dotNet should already be at a point of understanding recursion. If
not I will give a brief description of it first but I will not cover it in depth.
A recursive function is one that calls it self. In the case of the tool that we are developing we
need to be able to follow the hierarchy of nodes in the scene from the root down through all the children.
Since we don't know how many children there are, and how many children each child has we need recursion.
For each child the function will be called again, if that child has children it will call it self for each
of those children as well and so on down the hierarchy.
To get started with this we will need a variable to store all the root nodes of the scene in and a
function to find them all. This simply checks to see if the object has a parent in the scene and if not
it stores that object in rootObjs array that we define at the top of the rollout.
Code:
local rootObjs=#() --Will hold all the root nodes found in the scene.
--Find all the root objects in the scene and append them to rootObjs array
fn findRootObjs =
(
rootObjs=#()
for x in objects do
(
if x.parent==undefined then append rootObjs x
)
)
Next we will need the recursive function to loop down through all the children and add the nodes
to treeView. Since we already tried adding nodes directly to treeView and saw that it didn't work
we will need to add treeNodes to treeNodes. If you create a "System.Windows.Forms.TreeNode" in the
listener and check it's properties you can see that it also has a nodes property and the nodes property
has a .add method. Each time the function calls it self it passing to the new instance of the function
the node that it is working on and the treeNode that it added to treeView.
Code:
--Recurse hierarchy and add treeview nodes.
fn recurseHierarchy obj theTvNode =
(
for i = 1 to obj.children.count do --Loop through each of the children
(
n=(dotNetObject "System.Windows.Forms.TreeNode" obj.children[i].name)
theTvNode.nodes.add n
recurseHierarchy obj.children[i] n --Call recursion on each of the children.
)
)
I have changed the populateTreeView function so that it first calls the findRootObjs function and
then only loops through the root nodes of the scene. For each of the root nodes it adds a node to the
root of treeView and calls the recurseHierarchy function and passes the object it is working on and
the treeNode that it created for that object.
Code:
--Adds root nodes to treeView.
fn populateTreeView theTv=
(
findRootObjs() --Collect all the root objects.
--Loop through all the objects in the scene.
for x in rootObjs do
(
--Create a treeViewNode and add it to the treeView control
n=(dotNetObject "System.Windows.Forms.TreeNode" x.name)
theTv.nodes.add n
recurseHierarchy x n --Call recursive function on each of the root nodes.
)
)
Result:
|