This is obviously a very advanced topic, but it is very possible to create a graph completely in code. In this example bellow, a simple BehaviourTree is created.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
using UnityEngine; using NodeCanvas.Framework; using NodeCanvas.BehaviourTrees; using NodeCanvas.Tasks.Actions; //Attach this component on a gameobject that has a BehaviourTreeOwner already attached. public class CreateBTInCode : MonoBehaviour { void Awake(){ var owner = GetComponent<BehaviourTreeOwner>(); if (owner == null){ return; } //Create the Behaviour Tree var bt = ScriptableObject.CreateInstance<BehaviourTree>(); //Sequencer Node var seqNode = bt.AddNode<Sequencer>(); //First ActionNode var actNode1 = bt.AddNode<ActionNode>(seqNode.nodePosition + new Vector2(-100, 100)); var actTask1 = Task.Create<Wait>(bt); actTask1.waitTime = 1f; //set waitTime directly. actNode1.task = actTask1; //Second ActionNode var actNode2 = bt.AddNode<ActionNode>(seqNode.nodePosition + new Vector2(100, 100)); var actTask2 = Task.Create<Wait>(bt); actTask2.waitTime.name = "MyFloatVariable"; //set waitTime to read from a Blackboard Variable. actNode2.task = actTask2; //Connect the Nodes bt.ConnectNodes(seqNode, actNode1); bt.ConnectNodes(seqNode, actNode2); //Assign the BehaviourTree to the owner and enable it owner.StartBehaviour(bt); } |