GOAP for Unity

repository·master·Indexed 23 days ago

https://github.com/crashkonijn/goap

A high-performance, multi-threaded Goal Oriented Action Planning (GOAP) system for Unity (compatible with 2021.3 and 2022.2). It leverages Unity's Job System to facilitate complex AI behaviors, featuring a built-in Node Viewer for debugging, support for ScriptableObjects, and a decoupled architecture separating execution (AgentBehaviour) from decision-making (GoapActionProvider). Version 3.1.2.

Tokens
29K
Snippets
48
Records
101
Agent score
79%

What's inside crashkonijn-goap

  1. Overview of GOAP for Unity

    master

    GOAP (Goal Oriented Action Planning) for Unity is a high-performance, multi-threaded AI system designed to create complex agent behaviors.

    Key characteristics include:

    • Performance: Leverages Unity's Job System for multi-threaded operations.
    • Configuration: Supports both ScriptableObjects and code-based configurations.
    • Debugging: Includes a built-in Node Viewer to visualize GOAP nodes and AI decision-making.
    • Compatibility: Built for Unity 2022.2, but also compatible with Unity 2021.3.

    For detailed API references and guides, visit the official documentation at goap.crashkonijn.com or check the Package/Documentation folder in the repository.

  2. What is Goal Oriented Action Planning (GOAP)?

    master

    Goal Oriented Action Planning (GOAP) is an AI technique used to create autonomous agents that can determine their own sequences of actions to achieve specific goals.

    How it works:

    1. State Evaluation: The agent evaluates its current state and its desired goal state.
    2. Action Library: The agent searches through a library of available actions.
    3. Preconditions: Each action has a set of requirements (preconditions) that must be met before it can be executed (e.g., an 'Open Door' action might require the agent to be 'At Door').
    4. Planning: The agent finds a sequence of actions that transforms the current state into the goal state.
    5. Execution & Re-evaluation: The agent executes the plan step-by-step. After each action, it re-evaluates the environment. If the environment changes or an obstacle appears, the agent can dynamically generate a new plan to reach the goal.

    This approach allows NPCs to adapt to complex, changing environments and supports diverse behaviors by adjusting action or goal weightings.

  3. What are TargetKeys and how do they work?

    master

    In the GOAP system, TargetKeys are identifiers used to specify positions or locations within the game environment. They allow the Planner to calculate the distance and cost between Actions and the specific location an Agent must reach to execute an action.

    TargetKeys work in tandem with TargetSensors:

    • TargetKey: Acts as a label or identifier for a location.
    • TargetSensor: Responsible for mapping that label to a precise, up-to-date position in the game world.
  4. Understand AgentTypes and Capabilities

    master

    In the GOAP system, agent behavior is structured using two primary abstractions: AgentTypes and Capabilities.

    • AgentType: A classification or category for agents. It acts as a container for a set of Capabilities. All agents assigned to the same AgentType share the same goals, actions, and sensors.
    • Capability: A modular collection of specific goals, actions, and sensors (e.g., navigation, combat, or resource gathering).

    By combining multiple Capabilities into an AgentType, you can build complex, modular behaviors that are easy to manage and reuse across different agent categories.

  5. Manage WorldState with Sensors

    master

    The WorldState provides the current state of the world to the Resolver. To populate this state, you must implement Sensors.

    A Sensor is a class that reads values from your own MonoBehaviours and provides them to the WorldState.

    Key Types

    • WorldKey: References a value in the world. All WorldKey values must be represented by ints (e.g., AppleCount).
    • TargetKey: References a position in the world. All TargetKey values must be represented by Vector3 (e.g., AppleTree).

    Sensor Scopes

    • Global: Provides information applicable to all agents of an AgentType (e.g., IsDaytimeSensor).
    • Local: Provides information specific to a single agent (e.g., ClosestAppleSensor).
  6. Configure a Goal using GoalConfig

    master

    To define a goal's behavior and success criteria, you use GoalConfig. This configuration involves two primary components:

    1. Class Type: Specifies the exact type or category of the goal for identification within the system.
    2. Conditions: A set of criteria based on WorldKeys that must be met for the goal to be considered achieved. The Planner evaluates these conditions to select the best Action to align with the desired outcome.

    Example: A "Stay Safe" goal might have conditions using WorldKeys such as IsHealthHigh or IsInSafeZone.

  7. What are Sensors in GOAP

    master

    A Sensor is a class that reads the current state of the world and provides this information to the WorldState. The Resolver uses this information to determine the best action to perform based on the current state of the world.

    Sensors provide values for two types of data keys:

    • WorldKey: References a value in the world (e.g., AppleCount). All values must be represented by ints.
    • TargetKey: References a position in the world (e.g., AppleTree). All positions must be represented by Vector3.

    Sensors operate in two scopes:

    • Global: Provides information for all agents of an AgentType (e.g., IsDaytimeSensor).
    • Local: Provides information for a specific agent (e.g., ClosestAppleSensor).
    Data TypeLocal Base ClassGlobal Base Class
    WorldKeyLocalWorldSensorBaseGlobalWorldSensorBase
    TargetKeyLocalTargetSensorBaseGlobalTargetSensorBase
  8. How Conditions and Effects Match in GOAP

    master

    The GOAP planner matches conditions to effects to build action sequences. The matching logic follows these rules:

    • Lowering Values: Conditions using SmallerThan or SmallerThanOrEqual look for actions with negative effects (actions that decrease the WorldKey).
    • Increasing Values: Conditions using GreaterThan or GreaterThanOrEqual look for actions with positive effects (actions that increase the WorldKey).

    Example: If a goal requires AmmoCount to be GreaterThan 10, the planner will search for actions that have a positive effect on AmmoCount (like ReloadGun).

  9. Understand the Agent and Action Provider relationship in v3

    master

    In v3, the responsibilities of the AI have been split into two distinct components:

    1. AgentBehaviour: The entity that physically performs actions. It is a simple executor that knows how to take an action and perform it, but it does not decide which actions to take. It interacts with an IActionProvider.
    2. GoapActionProvider: The decision-making entity. It provides the actions available to the Agent and is responsible for deciding which actions to perform and when. It contains all GOAP-related methods (like RequestGoal) and interacts with an IActionReceiver.

    This separation allows for more flexible architectures where the decision logic (Provider) is decoupled from the physical execution (Behaviour).

  10. Implement Sensors for WorldKeys and TargetKeys

    master

    Sensors are used to provide values for WorldKey or TargetKey types by reading the current state of the world and providing it to the WorldState.

    The base class you must extend depends on the Type of key and the Scope of the sensor:

    Key TypeLocal Scope (Single Agent)Global Scope (All Agents)
    WorldKeyLocalWorldSensorBaseGlobalWorldSensorBase
    TargetKeyLocalTargetSensorBaseGlobalTargetSensorBase

    Sensor Lifecycle Methods:

    • Created(): Called when the sensor is initialized.
    • Update(): Called every frame an agent using this sensor needs it. Useful for caching data (e.g., finding the closest tree).
    • Sense(IActionReceiver agent, IComponentReference references, ITarget existingTarget): The core logic that returns the sensed value (e.g., a PositionTarget).
    using CrashKonijn.Agent.Core;
    using CrashKonijn.Goap.Runtime;
    using UnityEngine;
    
    namespace CrashKonijn.Docs.GettingStarted.Sensors
    {
        [GoapId("IdleTargetSensor-c34e9575-d171-4044-9b83-a91a1c32e214")]
        public class IdleTargetSensor : LocalTargetSensorBase
        {
            public override void Created() { }
    
            public override void Update() { }
    
            public override ITarget Sense(IActionReceiver agent, IComponentReference references, ITarget existingTarget)
            {
                var random = this.GetRandomPosition(agent);
    
                if (existingTarget is PositionTarget positionTarget)
                {
                    return positionTarget.SetPosition(random);
                }
    
                return new PositionTarget(random);
            }
    
            private Vector3 GetRandomPosition(IActionReceiver agent)
            {
                // Implementation logic...
                return Vector3.zero;
            }
        }
    }
  11. Implement the Agent and ActionProvider

    master

    To run a GOAP setup, you need an Agent and an ActionProvider:

    • ActionProvider (specifically GoapActionProvider): This class uses the Resolver to determine the best action based on the WorldState and requested goals. It then sets the action for the agent to perform. The GOAP system itself does not handle the execution of actions.
    • Agent: A GameObject containing the AgentBehaviour script. The AgentBehaviour is responsible for executing the action set by the ActionProvider. It will run the action until it is completed or stopped. If the action has a TargetKey, the agent will automatically move to that position before execution.