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 class. To create one, do the following:
Graph-
Create a new C# script file in thefolder of your Unity project.
Assets\Editor -
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}
-
Define a class that inherits from.
Graph -
Define anstring constant to specify your graph's file extension.
AssetExtension -
Apply theattribute, and pass your extension as a parameter.
[Graph] -
Mark your class withto ensure proper data persistence as you extend your graph tool.
[Serializable] -
Add a newfunction that calls the
CreateAssetFilemethod, and decorate this function with aPromptInProjectBrowserToCreateNewAssetattribute.MenuItem[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. Theconstant defines the file extension Unity uses to save your graph assets.AssetExtension