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 invoked through the behavior tree with the Send Event and the Has Received Event tasks. The Send Event task should be used when the event should be invoked. 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. For example:

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.

In addition to being able to send events via the behavior tree tasks, events can be sent through code. The EventHandler.ExecuteEvent method will allow you to send an event to the specified object. For example:

using Opsive.Shared.Events;

var behaviorTree = GetComponent<BehaviorTree>();
EventHandler.ExecuteEvent<object>(behaviorTree , "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: EventHandler.ExecuteEvent<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 EventHandler.RegisterEvent method. EventHandler.UnregisterEvent will stop listening for that event.

using Opsive.Shared.Events;

public void OnEnable()
{
   var behaviorTree = GetComponent<BehaviorTree>();
   EventHandler.RegisterEvent<object>(behaviorTree, "MyEvent", ReceivedEvent);
}

public void ReceivedEvent(object arg1)
{

}

public void OnDisable()
{
   var behaviorTree = GetComponent<BehaviorTree>();
   EventHandler.UnregisterEvent<object>(behaviorTree, "MyEvent", ReceivedEvent);
}