Search Unity

Question Add Visual Script component at runtime using C#

Discussion in 'Visual Scripting' started by shen0100, May 15, 2023.

  1. shen0100

    shen0100

    Joined:
    Dec 1, 2012
    Posts:
    3
    Is it possible to add a visual script graph component directly to a gameobject at runtime using C#?

    Senario: I have two script graphes named "test_a.asset" and "test_b.asset". I would like to use C# to decide and add one of the script graph to a gameobject at runtime.

    I know Unity has a Scripting API: GameObject.AddComponent, but I am not sure what params to pass. It seems I need to create a ScriptMachine with the graph asset path somehow, but I failed to find the implementation detail.
    I also realised that there is a node called "SetScriptGraph", but I cannot pass the graph asset path to it.
     
  2. PanthenEye

    PanthenEye

    Joined:
    Oct 14, 2013
    Posts:
    2,076
    Load it first and then pass in the actual asset? Lots of ways of loading assets in Unity from path. Resources.Load would probably be the simplest but ideally you'd use something like Addressables for it.
     
  3. shen0100

    shen0100

    Joined:
    Dec 1, 2012
    Posts:
    3
    Thanks for your reply! The Resources.Load worked with SetScriptGraph in visual scripting graph.

    Just curious, is it possible to use C# to do the same thing?
     
  4. PanthenEye

    PanthenEye

    Joined:
    Oct 14, 2013
    Posts:
    2,076
    It should be possible in C#. It's been a long time since I've used Visual Scripting in a project so I won't be able to help with the specifics.
     
  5. shen0100

    shen0100

    Joined:
    Dec 1, 2012
    Posts:
    3
    Thanks for the help. Will try to figure it out later.
     
  6. cworld

    cworld

    Joined:
    Feb 6, 2020
    Posts:
    8
    var asset=Resources.Load("xxxxxxx");
    var stateMachine = go.AddComponent<StateMachine>();
    stateMachine.nest.SwitchToMacro((StateGraphAsset)asset);