Events
The event system within Behavior Designer allows your behavior trees to easily react to changes. This event system can trigger an event via code or through behavior tree tasks.
Events can be signaled through the behavior tree with the Send Event and the Has Received Event tasks. When an event should be signaled, the Send Event task should be used. The Has Received Event task is a conditional task and will return success as soon as the event has been received. An event name can be specified for both of these tasks. In order to properly receive the events the Has Received Event task should be reevaluated with conditional aborts. As an example, consider the following tree:
During the first tick the Has Received Event task will fail because the event has not been received yet. The Selector will then move to the right branch and the Wait task will start. After a second the Send Event Task will send the event and then Idle is started to keep the tree active. During the next tick the Has Received Event task returns a status of success because of the previous event that was sent. It then outputs the value of the MyInt variable which was sent with the Send Event task.
In addition to being able to send events via the behavior tree, events can be sent through code. The BehaviorTree.SendEvent method will allow you to send an event to the specified behavior tree. For example:
var behaviorTree = GetComponent<BehaviorTree>(); behaviorTree.SendEvent<object>("MyEvent", 5);
In this example the “MyEvent” event will be sent to the behavior tree component with a parameter value of 5. If the behavior tree contains the Has Received Event task then it will react accordingly. If the Has Received Event task is receiving event then the template type must be a valid of object.
You are also able to receive events from outside the behavior tree. To continue with the “MyEvent” example, you can receive this event by using the BehaviorTree.RegisterEvent method. BehaviorTree.UnregisterEvent will stop listening for that event.
public void OnEnable() { var behaviorTree = GetComponent<BehaviorTree>(); behaviorTree.RegisterEvent<object>("MyEvent", ReceivedEvent); } public void ReceivedEvent(object arg1) { } public void OnDisable() { var behaviorTree = GetComponent<BehaviorTree>(); behaviorTree.UnregisterEvent<object>("MyEvent", ReceivedEvent); }