AI Framework - abackwood/TravellerEngine GitHub Wiki

Overview

At the core of the AI framework are two abstract classes and an interface:

  • AI
  • AIBehaviour
  • Action

AI

The AI class derives from MonoBehaviour. Any implementing class should be added as a component to a GameObject. To keep the internal AI workings separate from the external effects, the AI is paired to another MonoBehaviour component that represents the object, called the 'target'. This component is specified in the type parameter. A reference to the component is automatically obtained.

The AI class should be inherited like so:

[RequireComponent (typeof (SomeScript))
public class MyAI : AI<SomeScript> {
    protected override void Setup() {
        ...
    }
    ...
}

The Setup() method is called when the GameObject is loaded and should be used for initialization.

The AI class doesn't provide any repeating behaviour by itself. Through AddBehaviour() and RemoveBehaviour(), AIBehaviour objects are added and removed from the AI. These objects are the ones actually making the AI do something.

AIBehaviour

As the name suggests, these are the objects specifying what the AI acting and decision-making. The type parameter once again specifies the script being acted upon and must be the same as the AI it will be added to.

Start() has very similar functionality to the MonoBehaviour Start() method. It is called when the AIBehaviour is added to an AI object and should be used for any initialization.

Update() is the main function and is called regularly (though not necessarily every frame). Any repeating logic for the behaviour goes here.

Done() is called by AI before Update(). If it returns true, the behavious is removed from the AI. If a behaviour has no self-contained end condition, a simple 'return false' is acceptable. There are other ways to remove a behaviour so this does not mean it will execute forever.

Behaviours have references both to the AI and target object. However, they should never change the state of the target directly. The target reference should only be used to obtain information about the object state. State changes are handled through Action objects passed to the AI through the Do() method. This may seem circuitous but it puts authority on when to execute the actions with the central AI, not with the decentralized AIBehaviour.

Action

The type parameter of an Action defines the target it operates on.

IsAllowed() defines the precondition for the Action to be executed. This is checked both when it is added to the queue and when it is about to be executed. If the precondition fails, the action is skipped.

Execute() defines the effect on the target of executing the action.

NOTE: Ideally, IsAllowed() and Execute() don't change the state of the Action itself, so the object is reuseable.

⚠️ **GitHub.com Fallback** ⚠️