Modifying a Graph at Runtime - McManning/BlueGraph GitHub Wiki

While typically you will want to use the visual canvas to modify a Graph, some use cases may require a Graph asset to be adjustable outside of the editor. Here are a basic list of tips and pitfalls.

Also note that since the Graph is a ScriptableObject under the hood, you will need to follow all of Unity's rules for persisting ScriptableObject changes and any limitations that come from modifying SO's during runtime.

Adding Nodes Outside of the Canvas

If you want to add nodes to a graph via Graph.AddNode(new MyNode()) at runtime, there are a few caveats you need to watch out for.

The [Input] and [Output] attributes on fields cannot be used to automatically add BlueGraph.Port instances to the node, as our reflection tools are not available outside of the Unity Editor. Instead, you will need to manually add ports as part of the OnAddedToGraph event for you node.

For example, let's say we had a Graph that adds a new MyRuntimeNode node at runtime given some condition:

public class MyGraph : Graph
{
    void OnSomeCondition()
    {
        AddNode(new MyRuntimeNode());
    }
}

You will need to set Node.Name and call Node.AddPort manually within that node's OnAddedToGraph event:

/// <summary>
/// Node that gets added at runtime, and not through the editor
/// </summary>
public class MyRuntimeNode : Node
{ 
    public override void OnAddedToGraph()
    {
        Name = "Entry Point";

        AddPort(new Port
        {
            Name = "Foo Bar",
            Direction = PortDirection.Output,
            Type = typeof(float),
        });
    }
    
    ...
}

Modifying Edges Outside of the Canvas

Most edge operations on the canvas delegate to the Graph's Graph.AddEdge() and Graph.RemoveEdge() methods. Just make sure the canvas is not open while performing these operations, as the canvas does not automatically update if you make changes directly to the underlying graph asset.

Always make sure you add nodes to the graph before adding edges, and to use the Graph's methods for connecting nodes. This ensures the right events are fired.

⚠️ **GitHub.com Fallback** ⚠️