Add Visual Script component at runtime using C#

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.

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.

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?

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.

Thanks for the help. Will try to figure it out later.

var asset=Resources.Load(“xxxxxxx”);
var stateMachine = go.AddComponent();
stateMachine.nest.SwitchToMacro((StateGraphAsset)asset);