Context System

Give your NPCs situational awareness.

This page covers the Unity components that gather and send context. What each context field means (with examples and size limits) is documented once in the platform's Runtime Context guide.

Quick Start

Most games only need basic context. Set location and time:

csharp
using Peek.LoreMind;

var npc = GetComponent<LoreMindNPC>();
npc.SetLocation("Blacksmith Shop");
npc.Context.timeOfDay = "evening";

That's it! For automatic location updates and advanced features, read on.


Context Layers

The context system has three layers:

  1. Manual Context - Set directly on LoreMindNPC.Context
  2. Automatic Sensing - Detect nearby entities with LocationZone and ContextTag
  3. Global Context - Shared world state via GlobalContextManager

RuntimeContext

The RuntimeContext class holds situational information for NPC responses.

csharp
using Peek.LoreMind;

var npc = GetComponent<LoreMindNPC>();

npc.Context.location = "The Rusty Anvil Tavern";
npc.Context.timeOfDay = "evening";
npc.Context.atmosphere = "festive";
npc.Context.npcMood = "cheerful";

Available Fields

Location

  • location - Where the conversation happens (e.g., "The Rusty Tavern")
  • locationDetails - Additional description (e.g., "Crowded, dim lighting")

Environment

  • timeOfDay - dawn, morning, midday, afternoon, dusk, evening, night, midnight
  • weather - clear, rainy, stormy, foggy, snowing
  • atmosphere - peaceful, tense, festive, eerie, somber

Surroundings

  • nearbyCharacters - Array of visible character names
  • nearbyObjects - Array of notable objects

Situation

  • situation - Current interaction type (shopping, combat, exploring)
  • recentEvents - Recent game events the NPC would know about

NPC State

  • npcMood - cheerful, suspicious, nervous, tired, angry
  • npcActivity - What the NPC is doing (smithing, patrolling, tending bar)

Player Observation

  • playerAppearance - What the NPC sees (battle-worn, well-equipped, wounded)
  • playerReputation - How the NPC views the player (trusted ally, stranger, enemy)
  • playerVisibleItems - Notable items the player is carrying

Custom

  • SetCustom(key, value) - Key-value pairs for game-specific context

Example: Blacksmith Context

csharp
void OnPlayerEnterShop()
{
    npc.SetLocation("Blacksmith Shop", "Hot, smell of coal and metal");
    npc.Context.npcActivity = "hammering at the forge";
    npc.Context.playerAppearance = "carrying a damaged sword";
}

async void OnPlayerSpeak(string text)
{
    var response = await npc.RespondAsync(text);
    // NPC responds aware of the shop and damaged sword
}

LocationZone

Trigger-based zones that automatically update NPC location context.

LocationZone Setup

  1. Create a GameObject in your scene
  2. Add a trigger Collider (Box, Sphere, etc.)
  3. Add Component > LoreMind > Location Zone
  4. Configure location name and details

LocationZone Configuration

FieldDescription
Location NameName shown to NPCs (e.g., "The Rusty Anvil Tavern")
Location DetailsAdditional context (e.g., "Crowded, smoky")
WeatherOverride weather for this zone
AtmosphereOverride atmosphere for this zone
PriorityFor overlapping zones, higher wins
Clear On ExitClear location when NPC leaves

Example: Tavern Zone

text
Location Name: "The Rusty Anvil Tavern"
Location Details: "Crowded and loud, smell of ale and roasted meat"
Atmosphere: "rowdy"

When an NPC enters this zone, their context auto-updates:

csharp
// After NPC enters zone:
npc.Context.location == "The Rusty Anvil Tavern"
npc.Context.locationDetails == "Crowded and loud..."
npc.Context.atmosphere == "rowdy"

Overlapping Zones

When zones overlap, priority determines the winner:

csharp
// Zone A: "Town Square" (Priority: 0)
// Zone B: "Festival Grounds" (Priority: 10)

// NPC enters both → "Festival Grounds" wins (higher priority)

Nested Zones Pattern

Use nested zones for hierarchical locations:

text
Outer zone: "Castle Grounds" (Priority: 0)
Inner zone: "Throne Room" (Priority: 10)

NPC in throne room → "Throne Room"
NPC in courtyard → "Castle Grounds"

ContextTag

Mark GameObjects as perceivable by NPCs. When auto-sensing is enabled, NPCs detect nearby ContextTags.

ContextTag Setup

  1. Select a GameObject you want NPCs to perceive
  2. Add Component > LoreMind > Context Tag
  3. Set Display Name and Category

ContextTag Configuration

FieldDescription
Display NameHow this appears to NPCs (e.g., "Suspicious hooded figure")
CategoryCharacter, Object, Item, or Landmark
DetailsAdditional description when NPC is close
Details RadiusDistance within which details are visible

Categories

csharp
ContextCategory.Character  // NPCs, creatures, enemies
ContextCategory.Object     // Furniture, decorations, containers
ContextCategory.Item       // Weapons, tools, consumables
ContextCategory.Landmark   // Buildings, monuments, natural features

Example Tags

Suspicious Character:

text
Display Name: "Hooded figure"
Category: Character
Details: "Covered in dried blood, carries a strange amulet"
Details Radius: 3.0

Quest Item:

text
Display Name: "Enchanted sword"
Category: Item
Details: "Blade shimmers with frost magic"
Details Radius: 0 (always show details)

Enabling Auto-Sensing

csharp
npc.AutoSenseNearby = true;
npc.SenseRadius = 10f; // Adjust based on your game's scale
// Create these layers in Edit > Project Settings > Tags and Layers
npc.SenseLayers = LayerMask.GetMask("Characters", "Items");

The NPC now auto-detects tagged entities:

csharp
await npc.RespondAsync("Who else is here?");
// "Besides us, there's a suspicious merchant near that ancient altar."

Manual Sensing

Query detected entities directly:

csharp
IReadOnlyCollection<ContextTag> nearby = npc.NearbyEntities;

foreach (var entity in nearby)
{
    Debug.Log($"Detected: {entity.DisplayName} ({entity.Category})");
}

GlobalContextManager

Singleton for shared world state affecting all NPCs.

GlobalContextManager Setup

No setup required - it's a code-only singleton. Access it from anywhere via GlobalContextManager.Instance. State is in-memory and resets when play mode ends.

Usage

csharp
var global = GlobalContextManager.Instance;

// Time of day
global.SetTimeOfDay("dusk");

// World events
global.AddWorldEvent("The king has been assassinated");
global.AddWorldEvent("Refugees are fleeing the northern border");

// Custom context
global.SetCustom("war_status", "active");

Syncing with NPCs

Enable SyncGlobalContext on NPCs to auto-sync:

csharp
npc.SyncGlobalContext = true;

// Now when you update global time, all synced NPCs know:
GlobalContextManager.Instance.SetTimeOfDay("dusk");

Local context always takes priority over global context.

Event Subscription

React to global changes:

csharp
GlobalContextManager.Instance.OnContextChanged += () =>
{
    Debug.Log("Global context changed!");
};

Custom Context Providers

Integrate your game systems via INpcContextProvider. Quest systems, AI controllers, and inventory can provide context on-demand.

Implementation

csharp
using UnityEngine;
using Peek.LoreMind.Context;

public class QuestContextProvider : MonoBehaviour, INpcContextProvider
{
    public NpcContextData GetCurrentContext()
    {
        // Called just before NPC makes an API request
        return new NpcContextData
        {
            situation = GetCurrentSituation(),
            npcMood = GetNPCMood(),
            playerReputation = GetPlayerReputation(),
            recentEvents = GetRecentQuestEvents()
        };
    }

    private string GetCurrentSituation()
    {
        var quest = QuestManager.ActiveQuest;
        if (quest != null && quest.IsObjectiveActive("talk_to_innkeeper"))
            return "player_seeking_information";
        return null;
    }

    private string GetPlayerReputation()
    {
        int rep = FactionSystem.GetReputation("Innkeepers");
        if (rep > 75) return "trusted friend";
        if (rep > 25) return "known patron";
        if (rep < -25) return "troublemaker";
        return "stranger";
    }
}

Custom Provider Setup

  1. Attach the provider to the same GameObject as LoreMindNPC
  2. The NPC calls GetCurrentContext() automatically before each request
  3. Returned data merges with existing context

Context Layering

Context is gathered from multiple sources and merged:

  • Manual context (set directly on npc.Context)
  • LocationZone (trigger-based, auto-updates)
  • GlobalContextManager (if SyncGlobalContext enabled)
  • Auto-sensing (if AutoSenseNearby enabled)
  • Custom providers (if INpcContextProvider attached)

More specific context (manual settings, current location) takes precedence over general context (global settings).

The merge happens in a separate copy for each request, so npc.Context itself is never written during a request. Global time of day, world events and sensed nearby characters and objects go into that copy only: reading npc.Context.nearbyCharacters, nearbyObjects, timeOfDay or recentEvents after a request shows only the values your own code set.

Best Practices

Only Send Relevant Context

csharp
// BAD: Too much irrelevant context
npc.Context.playerVisibleItems = InventorySystem.GetAllItems(); // 50 items

// GOOD: Only notable items
npc.Context.playerVisibleItems = new[] { "Royal insignia", "Wanted poster" };

Update Context Just-In-Time

Update right before conversations, not every frame:

csharp
void OnPlayerInteract()
{
    npc.Context.playerAppearance = GetPlayerAppearance();
    npc.Context.playerReputation = GetPlayerReputation();
    StartDialogue();
}

Use LocationZones for Static Areas

Set up once in the scene, NPCs auto-update. Better than manually setting location for every NPC.

Use GlobalContextManager for Time/Weather

csharp
// BAD: Update each NPC
foreach (var npc in allNPCs)
    npc.Context.timeOfDay = "evening";

// GOOD: Update global state once
GlobalContextManager.Instance.SetTimeOfDay("evening");
// NPCs with SyncGlobalContext=true auto-sync

Limit Event History

csharp
// BAD: Too many events
npc.Context.recentEvents = EventLog.GetAll(); // 100 events

// GOOD: Most recent, relevant events
// Choose a count that balances context with token usage
npc.Context.recentEvents = EventLog.GetRecent(maxRecentEvents);

Next Steps