Documentation

Unity Engine

Unity Engine

Implement a graph tool

Create and implement a graph tool to visualize and manage complex data structures in Unity.
Read time 2 minutesLast updated 15 days ago

Create and implement a graph tool to visualize and manage complex data structures in Unity.

Prerequisites

None.

Define a custom Graph class

The foundation of any Graph Toolkit tool is a custom
Graph
class. To create one, do the following:
  1. Create a new C# script file in the
    Assets\Editor
    folder of your Unity project.
  2. Import the necessary namespaces:
    using System;using UnityEditor;using UnityEngine;using Unity.GraphToolkit.Editor;#endregion Importsnamespace Unity.GraphToolkit.Scripts.Editor{ #region SimpleGraph [Graph(AssetExtension)] [Serializable] class MySimpleGraph : Graph { public const string AssetExtension = "simpleg"; [MenuItem("Assets/Create/Graph Toolkit Samples/Simple Graph", false)] static void CreateAssetFile() { GraphDatabase.PromptInProjectBrowserToCreateNewAsset<MySimpleGraph>(); } } #endregion SimpleGraph class MyCustomType : ScriptableObject { } #region SimpleNode [Serializable] class MySimpleNode : Node {} #endregion SimpleNode #region SimpleNodeWithPorts [Serializable] class MySimpleNodeWithPorts : Node { protected override void OnDefinePorts(IPortDefinitionContext context) { context.AddInputPort<float>("Input").Build(); context.AddOutputPort<MyCustomType>("Output").Build(); } } #endregion SimpleNodeWithPorts}
  3. Define a class that inherits from
    Graph
    .
  4. Define an
    AssetExtension
    string constant to specify your graph's file extension.
  5. Apply the
    [Graph]
    attribute, and pass your extension as a parameter.
  6. Mark your class with
    [Serializable]
    to ensure proper data persistence as you extend your graph tool.
  7. Add a new
    CreateAssetFile
    function that calls the
    PromptInProjectBrowserToCreateNewAsset
    method, and decorate this function with a
    MenuItem
    attribute.
    [Graph(AssetExtension)] [Serializable] class MySimpleGraph : Graph { public const string AssetExtension = "simpleg"; [MenuItem("Assets/Create/Graph Toolkit Samples/Simple Graph", false)] static void CreateAssetFile() { GraphDatabase.PromptInProjectBrowserToCreateNewAsset<MySimpleGraph>(); } } #endregion SimpleGraph class MyCustomType : ScriptableObject { } #region SimpleNode [Serializable] class MySimpleNode : Node {} #endregion SimpleNode #region SimpleNodeWithPorts [Serializable] class MySimpleNodeWithPorts : Node { protected override void OnDefinePorts(IPortDefinitionContext context) { context.AddInputPort<float>("Input").Build(); context.AddOutputPort<MyCustomType>("Output").Build(); } } #endregion SimpleNodeWithPorts}
    This basic implementation creates the core structure for your graph tool. The
    AssetExtension
    constant defines the file extension Unity uses to save your graph assets.

Additional resources