Search Unity

Showcase Code to programmatically add a literal node to a flow graph

Discussion in 'Visual Scripting' started by termway, Mar 11, 2023.

  1. termway

    termway

    Joined:
    Jul 5, 2012
    Posts:
    85
    I spent some time to understand how to add a literal to a flow graph. I did not found this information elsewhere, so here it is:

    Code (CSharp):
    1.  
    2. using System.Reflection;
    3. using System.Linq;
    4. using Unity.VisualScripting;
    5. using UnityEngine;
    6.  
    7. public class AddFlowGraphLiteral : MonoBehaviour
    8. {
    9.     [SerializeField] ScriptMachine scriptMachine;
    10.  
    11.     [ContextMenu(nameof(Start))]
    12.     void Start()
    13.     {
    14.         // If you want to add this a newly created ScriptMachine.
    15.        // scriptMachine.nest.SwitchToEmbed(flowGraph);
    16.         Rigidbody rigidbody = GetComponent<Rigidbody>();
    17.         LiteralOption rigidbodyLiteral = new LiteralOption(new Literal(typeof(Rigidbody), rigidbody));
    18.         rigidbodyLiteral.unit.position = new Vector2(300, 300);
    19.    
    20.         MethodInfo methodInfo = typeof(Rigidbody).GetMethod(nameof(rigidbody.Sleep), BindingFlags.Instance | BindingFlags.Public);
    21.         Member member = MemberUtility.ToManipulator(methodInfo, typeof(Rigidbody));
    22.         InvokeMemberOption sleepInvoke = new InvokeMemberOption(new InvokeMember(member));
    23.         sleepInvoke.unit.position = new Vector2(600, 300);
    24.        
    25.         scriptMachine.graph.units.Add(rigidbodyLiteral.unit);
    26.         scriptMachine.graph.units.Add(sleepInvoke.unit);
    27.    
    28.         scriptMachine.graph.valueConnections.Add(new ValueConnection(rigidbodyLiteral.unit.valueOutputs.First(), sleepInvoke.unit.valueInputs.First()));
    29.     }
    30. }
    31.  
    upload_2023-3-11_17-6-47.png

    If you want to want more information and if you have specific need you can debug it yourself with a breakpoint in the LudiqGUI.FuzzDropdown() method (the callback(option.value) line. You will need the VisualScripting Registry packages (in Preferences > External Tools > Generate .csproj files for: > Registry packages)

    There are some modifications needed for properties...
     
    Last edited: Mar 11, 2023
    myanko, iScriptz and PanthenEye like this.