Source file unity-csharp/game-ai/goap/GoapAction.cs from the GDnD code examples. Download raw file
// GDnD wiki example
// Demonstrates: a GOAP action = name + cost + preconditions + effects (+ where and how long, for execution)
// Related pages: [[goal-oriented-action-planning]]
using System.Collections.Generic;
using UnityEngine;
// The planner only reads Cost, Preconditions and Effects. Target and Duration are
// for the agent that carries the action out: walk to Target, work for Duration seconds.
public class GoapAction
{
public string Name;
public float Cost;
public Transform Target;
public float Duration;
public Dictionary<string, bool> Preconditions = new();
public Dictionary<string, bool> Effects = new();
public GoapAction(string name, float cost, Transform target, float duration)
{
Name = name;
Cost = cost;
Target = target;
Duration = duration;
}
// Fluent helpers so actions read like a rule: Needs("HasAxe", true).Gives("HasWood", true)
public GoapAction Needs(string fact, bool value) { Preconditions[fact] = value; return this; }
public GoapAction Gives(string fact, bool value) { Effects[fact] = value; return this; }
public WorldState ApplyTo(WorldState state)
{
var next = new WorldState(state);
foreach (var effect in Effects) next.Set(effect.Key, effect.Value);
return next;
}
public override string ToString() => Name;
}