Skip to content

Common Design Patterns

Chase edited this page Oct 26, 2020 · 8 revisions

This is a collection of useful design patterns while working with the framework.

Creating a Graph Asset with Default Nodes

Sometimes you may want to have a set of nodes already placed when you create a new graph asset (e.g. an entry point or exit point).

You can use the included reflection tooling to instantiate a node on your graph, as long as it is being done within the editor.

public class MyGraph : Graph
{
    protected override void OnGraphEnable()
    {   
        #if UNITY_EDITOR
        if (GetNode<MyEntryPoint>() == null)
        {
            var node = NodeReflection.Instantiate<MyEntryPoint>();
            AddNode(node);
        }
        #endif
    }
}

If you want to ensure MyEntryPoint cannot be added or deleted by developers via the Canvas, give it a tag not in the [IncludeList] for the Graph (e.g. "Hidden") and set [Node(deletable = false)].

Adding IMGUI Content to a NodeView

If you want to add IMGUI content to a node, you will need to add a container wrapper to listen to IMGUI's OnGUI.

Add a custom NodeView for your node and in the OnInitialize() add an IMGUIContainer for your content:

using UnityEngine;
using UnityEngine.UIElements;
using UnityEditor;
using BlueGraph;

namespace BlueGraphSamples
{
    /// <summary>
    /// Custom NodeView for the `Say` node.
    /// 
    /// Displays a multiline editor for the text content.
    /// </summary>
    [CustomNodeView(typeof(Say))]
    public class SayNodeView : NodeView
    {
        protected override void OnInitialize()
        {
            // Setup a container to render IMGUI content in 
            var container = new IMGUIContainer(OnGUI);
            extensionContainer.Add(container);
            
            // Currently needed by Unity's base Node class to properly
            // resize for extensionContent.
            RefreshExpandedState();
        }
        
        void OnGUI()
        {
            // Call your EditorGUILayout methods here.
        }
    }
}