Skip to content

Tree

The Tree class allows to create acyclic dependency graphs that start from a root node and end with leaf nodes. A single node can have an unlimited number of branches.

To create a Tree, inherit from the Tree<T> class, where T is the value type of the node. For example, to create a tree of game objects:

public MyTree : Tree<GameObject>
{ }
public MyComponent : MonoBehaviour
{
    public MyTree tree = new MyTree();

    private void Awake()
    {
        // Add element:
        this.tree.AddChild(this.gameObject);

        foreach (var child in this.tree)
        {
            // Print child id:
            Debug.Log(child.Value.id);

            // Print child game object:
            Debug.Log(child.Value.Data.name);
        }
    }
}

A Tree<T> class is both the tree and the node class. So any child of a tree returns a tree object too. A tree can return its parent:

MyTree parent = this.tree.Parent

And it's children, which is a dictionary indexed by its Ids:

KeyValuePair<string, GameObject> = this.tree.Children;
Back to top