How to set shared variable on instantiated prefab with BT added at runtime?

Oxbox

New member
Hi. I'm new to Behavior Trees and trying to wrap my head around how to attach an external BT to an instantiated prefab. I'm using the pro version. After a lot of searching through the forums, I've come up with this. The problem is that my shared variable doesn't seem to exist in the game. I *think* it has something to do with project level scope, but I'm confused how to get around this.

I created a .asset file of my BT by using the Export function. That original BT was working just fine (especially the Graph's shared "Target" variable). Here's what shows up in the inspector (not run time). The "Target" variable is visible. This is on the Graph scope in the script.
1748525152423.png

I have a Spawner class that instantiates a prefab and attaches the BT. Here's what I got that almost works:
C#:
[SerializeField] private GameObject m_PrefabToSpawn;
[SerializeField] private Subtree m_BehaviorTree;
[SerializeField] private GameObject m_DefaultTargetToSeek;

...
    
Vector3 spawnPosition = new Vector3(Random.Range(-10f, 10f), 0, Random.Range(-10f, 10f));
GameObject enemy = Instantiate(m_PrefabToSpawn, spawnPosition, Quaternion.identity);
var bt = enemy.AddComponent<BehaviorTree>();
bt.StartWhenEnabled = true;
bt.Subgraph = m_BehaviorTree;
bt.SetVariableValue("Target", m_DefaultTargetToSeek);

When I play the scene, I can see that the Behavior Tree component is added and the Subtree is the there, but there are no variables. 1748525685853.png

Here is my BT on the instantiated prefab:
1748525814967.png

So to be clear, the BT tree is being attached correctly without errors, but I lost the ability to set the variable which breaks the functionality. I tried ReevaluateSubtreeReferences, setting the scope in SetVariableName, and using Project variables instead of Graph. I'm very new to this so I'm probably missing something simple. Thanks for any help.
 
The variables are synchronized within the editor when a behavior tree is assigned. I will add support for this use case in the next update.
 
Thanks. In the meantime, is there another way to handle this? Should I attach the BT directly to the prefab?
 
Back
Top