-
Notifications
You must be signed in to change notification settings - Fork 36
Modifying a Graph at Runtime
While typically you will want to use the canvas editor 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, if your use case requires it.
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.
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 of your node 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 constructor for you node.
For example, let's say we had a Graph that adds a new EntryPoint node at runtime given some condition:
public class MyGraph : Graph
{
void OnEnable()
{
if (SomeConditionHappens)
{
AddNode(new MyRuntimeNode());
}
}
}You will need to set Node.Name and call Node.AddPort manually within that node's constructor. Note that when nodes are later deserialized with the graph the constructor is skipped, so adding ports will only be done when you instantiate it via new EntryPoint().
/// <summary>
/// Node that gets added at runtime, and not through the editor
/// </summary>
public class MyRuntimeNode : Node
{
public MyRuntimeNode(): base()
{
// Since this node is created via `new` within MyGraph,
// we need to manually insert the expected ports/metadata
// that would be typically added via editor reflection.
name = "Entry Point";
AddPort(new Port
{
name = "Foo Bar",
direction = PortDirection.Output,
type = typeof(float),
});
}
...
}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.