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:
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:
- Manual Context - Set directly on
LoreMindNPC.Context - Automatic Sensing - Detect nearby entities with
LocationZoneandContextTag - Global Context - Shared world state via
GlobalContextManager
RuntimeContext
The RuntimeContext class holds situational information for NPC responses.
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, midnightweather- clear, rainy, stormy, foggy, snowingatmosphere- peaceful, tense, festive, eerie, somber
Surroundings
nearbyCharacters- Array of visible character namesnearbyObjects- 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, angrynpcActivity- 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
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
- Create a GameObject in your scene
- Add a trigger Collider (Box, Sphere, etc.)
- Add Component > LoreMind > Location Zone
- Configure location name and details
LocationZone Configuration
| Field | Description |
|---|---|
| Location Name | Name shown to NPCs (e.g., "The Rusty Anvil Tavern") |
| Location Details | Additional context (e.g., "Crowded, smoky") |
| Weather | Override weather for this zone |
| Atmosphere | Override atmosphere for this zone |
| Priority | For overlapping zones, higher wins |
| Clear On Exit | Clear location when NPC leaves |
Example: Tavern Zone
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:
// 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:
// 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:
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
- Select a GameObject you want NPCs to perceive
- Add Component > LoreMind > Context Tag
- Set Display Name and Category
ContextTag Configuration
| Field | Description |
|---|---|
| Display Name | How this appears to NPCs (e.g., "Suspicious hooded figure") |
| Category | Character, Object, Item, or Landmark |
| Details | Additional description when NPC is close |
| Details Radius | Distance within which details are visible |
Categories
ContextCategory.Character // NPCs, creatures, enemies
ContextCategory.Object // Furniture, decorations, containers
ContextCategory.Item // Weapons, tools, consumables
ContextCategory.Landmark // Buildings, monuments, natural featuresExample Tags
Suspicious Character:
Display Name: "Hooded figure"
Category: Character
Details: "Covered in dried blood, carries a strange amulet"
Details Radius: 3.0Quest Item:
Display Name: "Enchanted sword"
Category: Item
Details: "Blade shimmers with frost magic"
Details Radius: 0 (always show details)Enabling Auto-Sensing
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:
await npc.RespondAsync("Who else is here?");
// "Besides us, there's a suspicious merchant near that ancient altar."Manual Sensing
Query detected entities directly:
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
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:
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:
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
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
- Attach the provider to the same GameObject as
LoreMindNPC - The NPC calls
GetCurrentContext()automatically before each request - 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
SyncGlobalContextenabled) - Auto-sensing (if
AutoSenseNearbyenabled) - Custom providers (if
INpcContextProviderattached)
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
// 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:
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
// 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-syncLimit Event History
// 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
- LoreMindNPC Component - Complete component guide
- Long-Term Memory - NPCs remember players across sessions
- Voice Input - Voice integration
- API Reference - Complete API documentation