Gaining Control of Units

So how does a unit decide which behaviour to activate? Priorities and elections.

What Happens When a Behaviour is Activated?

Only one behaviour can by actively controlling a unit at a time. When a behaviour is chosen to control the unit, Activate is called, giving it a chance to issue initial orders and change variables. There is also a Deactivate function for when a behaviour loses control of the unit.

These functions are called by the UnitHandler module, you don’t have to call them yourself when writing behaviours.

How Does The Unit Choose The Active Behaviour?

Through a priority system/election! The Unit asks each behaviour what its current priority is, and activates the behaviour that returns the highest number. That behaviour now controls the unit.

Behaviours can return different priorities depending on the situation. For example, a behaviour that makes a unit flee may give a priority of 0 if no enemy units are nearby. But that might change to 100 if an enemy army passes close.

Another example, is the boot behaviour. It returns an incredibly high priority on new units, but once it’s finished what it needs to do, it returns 0 as a priority, and calls the ElectBehaviour method so that another behaviour can take control

When Does The Unit Change Behaviours?

The unit will poll behaviours when the UnitBuilt event occurs for that unit. From then on, any change in active behaviour happens when the behaviours themselves trigger it.

To do this, a behaviour calls  self.unit:ElectBehaviour() which triggers behaviour selection. A behaviour might do this because it has completed what it set out to do, or because of an emergency, such as a builder unit under attack.

Until a behaviour does this, it has exclusive control and will remain the active behaviour until a new election occurs. Any behaviour on the unit can do this though, as all behaviours receive events, even when inactive.

Issuing Orders

Behaviours always receive events, and it might be tempting to act on them. However, a behaviour must check if it is the active behaviour before issuing any orders. Otherwise, it might interfere with another behaviours functionality.