Behaviours

This is a system that specifies how a unit object behaves. Unit objects don’t issue commands or have behavioural logic inside them. Instead they contain behaviour objects that do the job of controlling the unit. Unit objects pass along events to these objects, and determine which behaviour is currently in control of the unit.

The TLDR of How Behaviours Work

It’s the behaviours that issue the unit commands, and its behaviours that control the unit.

At any one time, only a single behaviour is active, the active behaviour controls the unit, and can issue commands with total control. The unit picks the active behaviour by asking every behaviour for a priority, and the behaviour that returns the highest number wins. A behaviour can call self.unit:ElectBehaviour()to give up control or take control by triggering a new priority check.

Basic Code Structure of a Behaviour

A behaviour implements a basic structure, here’s the simplest behaviour possible:


NullBehaviour = class(Behaviour)

function NullBehaviour:Init()
	local u = self.unit:Internal()
	self.id = u:ID()
	self.name = u:Name()
	self.finished = false
end

function NullBehaviour:OwnerBuilt()
	self.finished = true
end

function NullBehaviour:Update()
	if self.finished then
		--
	end
end

function NullBehaviour:Activate()
	self.active = true
end

function NullBehaviour:Deactivate()
	self.active = false
end

function NullBehaviour:Priority()
	return 1
end

This behaviour doesn’t do anything, but it implements the important parts needed for a behaviour to work

How Behaviours Control Units

A unit will have several behaviours assigned to it, but only 1 behaviour is active at any one time. This is the active behaviour that has control of the unit, hence the activate and deactivate functions in the behaviour.