Setting BehaviorReference variables during runtime

mubarak

New member
I want to set the variables of a BehaviorReference during runtime. I created a class that inherits from BehaviorReference and overrides the
GetExternalBehaviors function. However, I could not do the same for the variables.

What I want to do is to have fields shown in the UI that will later be converted to Variables. That is because it is easy to forget to set the needed variables otherwise. The image below shows what I want to do.

1742350084197.png

My attempt is to set the "variables" field directly:
1742350502373.png
where CreateSharedNameVariable is:
1742350547116.png

However, it does not work. The external tree does not recognize the values of these variables.
 
Well I solved it. I was setting the variables inside the "OnAwake" method which doesnt work. Instead I should set the variables before that. In my case, I set them in the "Awake" method of one of the NPC's components:
C#:
void Awake() {
var tree = GetComponent<BehaviorDesigner.Runtime.BehaviorTree>();
tree.DisableBehavior();
var source = tree.GetBehaviorSource();
var externalTrees = tree.FindTasks<ExternalTree>();
foreach (var externalTree in externalTrees) {
     externalTree.Initialize();
}
tree.EnableBehavior();
}

ExternalTree is a class that derives from BehaviorReference

C#:
using UnityEngine;
using BehaviorDesigner.Runtime;
using BehaviorDesigner.Runtime.Tasks;
public class ExternalTree: BehaviorReference
{
    public SharedExternalBehaviour tree;
    public override ExternalBehavior[] GetExternalBehaviors() {
        return new ExternalBehavior[]{tree.Value};
    }
    public virtual SharedNamedVariable[] GetSharedNamedVariables() {
        return null;
    }
    public void Initialize() {
        variables = GetSharedNamedVariables();
    }
    public static SharedNamedVariable CreateSharedNamedVariable<T>(T sharedVariable, string name) where T: SharedVariable {
        var namedVariable = new NamedVariable();
        namedVariable.value = sharedVariable;
        namedVariable.type = typeof(T).Name;
        namedVariable.name = name;
        return namedVariable;
    }
}

and then I override GetSharedNamedVariables in each class that inherits from ExternalTree.
Kindly confirm that this is the appropriate way of settings the variables. Thanks.
 
Back
Top