Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

How to run a FlowGraph from C# and get the value from ControlOutput

Discussion in 'Visual Scripting' started by Opeth001, May 11, 2022.

  1. Opeth001

    Opeth001

    Joined:
    Jan 28, 2017
    Posts:
    1,078
    Hello everyone,

    I'm trying to create Abilities defined by Scriptable Objects (SO) using Bolt's FlowGraph to make it easier for designers.
    but I couldn't figure out how to execute FlowGraphs and get the generated SOs via C# scripts.

    Thanks!
     
  2. RedBjorny

    RedBjorny

    Joined:
    Nov 29, 2016
    Posts:
    19
    Hi!

    Did you find any solution?
     
  3. RedBjorny

    RedBjorny

    Joined:
    Nov 29, 2016
    Posts:
    19
    I created a method that is quite crude in its implementation and was wondering if there is a more elegant solution available.

    Code (CSharp):
    1.  
    2. public static class ScriptGraphAssetExtensions
    3. {
    4.     public static T Run<T>(this Unity.VisualScripting.ScriptGraphAsset graph, string method, object arg, string outputVariable) where T : class
    5.     {
    6. #if UNITY_EDITOR
    7.        if (!Application.isPlaying)
    8.        {
    9.            return default(T);
    10.        }
    11. #endif
    12.        var go = new GameObject("Temp");
    13. #if VISUALSCRIPTING_1_7_1_OR_GREATER
    14.        go.AddComponent<Unity.VisualScripting.ScriptMachine>().nest.SwitchToMacro(graph);
    15. #else
    16.        go.AddComponent<Unity.VisualScripting.FlowMachine>().nest.SwitchToMacro(graph);
    17. #endif
    18.        Unity.VisualScripting.CustomEvent.Trigger(go, method, arg);
    19.        var variables = Unity.VisualScripting.Variables.Object(go);
    20.        object output = default(T);
    21.        if (variables.IsDefined(outputVariable))
    22.        {
    23.            output = variables.Get(outputVariable);
    24.        }
    25.        GameObject.Destroy(go);
    26.        return output as T;
    27.     }
    28. }
    29.