LoreMindNPC Component
The LoreMindNPC component gives any GameObject conversational AI. Add it to your NPC and start talking.
Quick Start
var npc = GetComponent<LoreMindNPC>();
var response = await npc.RespondAsync("Hello!");
if (response.success)
Debug.Log(response.response);Required: Select an Entity Mind from the dropdown in the Inspector.
Required vs Optional Settings
| Setting | Required? | What it does |
|---|---|---|
| Entity Mind | Yes | The NPC's personality and knowledge |
| Location | No, but recommended | Where the conversation happens |
| Time of Day | No | Affects NPC responses ("It's getting late...") |
| Everything else | No | Advanced features you can add later |
Start simple. Just set the Entity Mind and start talking.
Talking to Your NPC
Async/Await Pattern
using UnityEngine;
using Peek.LoreMind;
using Peek.LoreMind.Cloud;
using Peek.LoreMind.Cloud.Data;
public class NPCDialogue : MonoBehaviour
{
[SerializeField] private LoreMindNPC npc;
public async void OnPlayerInteract(string playerMessage)
{
// Never null, and never throws for a failed request
var response = await npc.RespondAsync(playerMessage);
if (response.success)
{
ShowDialogue(response.response);
}
else
{
HandleError(response);
}
}
void ShowDialogue(string text)
{
// Display in your dialogue UI
dialogueUI.ShowText(text);
}
void HandleError(NPCResponse response)
{
// Never show made-up dialogue on failure: show a "try again" state instead
switch (response.error)
{
case LoreMindErrorCodes.InsufficientCredits:
Debug.LogError("Out of credits! Add more at loremind.peekgames.dev");
break;
case LoreMindErrorCodes.RateLimited:
case LoreMindErrorCodes.LoreUnavailable:
Debug.LogWarning($"{response.message} Try again in {response.retryAfter}s.");
break;
default:
Debug.LogWarning($"NPC error {response.error}: {response.message}");
break;
}
}
}Event Pattern
Don't want async/await? Use Unity Events:
void Start()
{
npc.OnResponseReceived.AddListener(OnNPCResponse);
npc.OnError.AddListener(OnNPCError);
}
void OnPlayerSpeaks(string text)
{
npc.Respond(text); // Fire and forget
}
void OnNPCResponse(string npcText)
{
dialogueUI.ShowText(npcText);
}
void OnNPCError(string error)
{
Debug.LogError($"NPC Error: {error}");
}Wire up events in the Inspector too, no code needed.
What Happens on Every Request
Every call to Respond / RespondAsync ends in exactly one outcome:
| Outcome | Events, in order | RespondAsync returns |
|---|---|---|
| Reply | OnResponseReceived(text), OnResponseComplete(response), then OnRequestFinished(response) | success = true |
Failure (network, API error, CONFIG_ERROR, ...) | OnError(message), then OnRequestFinished(response) | success = false, error set |
| Empty player text | OnRequestFinished(response) | EMPTY_TEXT |
| Called while the NPC is still answering | none | BUSY |
| NPC destroyed (or Play mode exited) while waiting, or called on an NPC already destroyed | none | CANCELLED |
OnRequestFinished fires once per request, success or not: it's the place to hide a "thinking" indicator. Check response.success before showing response.response, or a listener shows an empty bubble on an error. OnResponseComplete fires only for a reply. A BUSY call fires no event, so it never ends the wait for the request still running. An exception thrown by one of your listeners is logged and doesn't change the outcome or stop the other events.
npc.OnRequestFinished.AddListener(response =>
{
thinkingIndicator.SetActive(false);
sendButton.interactable = true;
if (!response.success)
dialogueUI.ShowTryAgain(); // never a made-up line
});Checking If NPC Is Busy
The component won't send a new request while one is in progress. A second call returns a BUSY error without sending anything or firing events:
if (npc.IsProcessing)
{
Debug.Log("NPC is thinking...");
return;
}
await npc.RespondAsync(playerInput);Cancelling a Request
A request is cancelled automatically when the NPC is destroyed or Play mode ends. To cancel it yourself (for example when the player walks away), pass a CancellationToken:
using System.Threading;
var cts = new CancellationTokenSource();
var response = await npc.RespondAsync("Tell me a long story", cts.Token);
// Elsewhere: cts.Cancel(); -> the web request is aborted and response.error is CANCELLEDAdding Context
NPCs give better responses when they know where they are.
Location
npc.SetLocation("The Rusty Anvil Tavern", "Crowded, late evening");
var response = await npc.RespondAsync("Is it always this busy?");
// "Aye, especially on market days! Though it's usually quieter by midnight."Time and Weather
npc.Context.timeOfDay = "midnight";
npc.Context.weather = "stormy";
var response = await npc.RespondAsync("Should I head out?");
// "In this storm? At this hour? I wouldn't recommend it, friend."Custom Context
Add any game-specific context:
npc.SetCustomContext("player_reputation", "respected");
npc.SetCustomContext("active_quest", "Find the missing merchant");
var response = await npc.RespondAsync("Need any help around here?");
// NPC references the quest and treats the player accordinglyMulti-Turn Conversations
The NPC automatically remembers what you talked about:
await npc.RespondAsync("What's your name?");
// "I'm Garrick, innkeeper here for twenty years."
await npc.RespondAsync("Twenty years? That's impressive!");
// NPC remembers what they just saidClear history when conversation ends:
void OnPlayerLeave()
{
npc.ClearConversationHistory();
}Otherwise the next conversation continues from where you left off.
Response Configuration
Response length (verbosity) is configured per Entity Mind in the LoreMind dashboard. The dashboard is the single source of truth; there are no SDK-side overrides.
| Setting | Dashboard Location | Effect |
|---|---|---|
| Verbosity | Entity Mind → Response Length | Terse (1-2 sentences), Balanced (2-4), or Verbose |
Active Knowledge Tags
Restrict which lore an NPC can reference at runtime, for example to gate knowledge behind quest progression or story beats. ActiveKnowledgeTags narrows which of the Entity Mind's lore tags the NPC can use for the next requests. It can only restrict, never expand, what the Entity Mind can access.
Setting Tags at Runtime
// Early game: NPC only knows about blacksmithing
npc.ActiveKnowledgeTags = new[] { "blacksmithing" };
// After player completes a quest, unlock more knowledge
void OnQuestComplete(string questId)
{
if (questId == "discover-ruins")
{
npc.ActiveKnowledgeTags = new[] { "blacksmithing", "ancient-ruins" };
}
}
// Clear to restore full Entity Mind knowledge
npc.ActiveKnowledgeTags = null;Limits and Unknown Tags
- At most 50 tags of at most 100 characters each, none of them
null, empty or whitespace. Anything else is reported asVALIDATION_ERRORand nothing is sent. A blank element left in the Inspector list fails the request too. - Tags the Entity Mind doesn't have are ignored and listed in
response.metadata.warnings, which the built-in transports show as Console warnings in the Editor and Development Builds, whatever the Log Level. - If none of the tags exist on the Entity Mind, the request fails with
UNKNOWN_KNOWLEDGE_TAGS: no reply, no credits used. The NPC never answers without lore. Compare the tags with the Entity Mind's tags in the dashboard (a renamed or removed tag is the usual cause), or set the property tonullto use all of the mind's tags again.
Inspector
The Knowledge Gating foldout in the Inspector lets you set default active tags without code. Tags set in the Inspector are used unless overridden at runtime.
Upgrading from SDK 1.0.8 or earlier: saved Active Knowledge Tags now take effect, so NPCs with saved tags may answer from less lore. Check the tags on your NPCs.
See Entity Minds: Active Knowledge Tags for the platform-level overview.
Context Awareness (Advanced)
Auto-Sense Nearby Entities
NPCs can automatically detect nearby characters and objects with ContextTag components:
npc.AutoSenseNearby = true;
npc.SenseRadius = 10f; // Adjust based on your game's scale
// NPC now knows about nearby tagged entities
var response = await npc.RespondAsync("Who else is here?");
// "Besides us, there's a suspicious merchant near that altar."Sync Global Context
Automatically sync time/weather from GlobalContextManager:
npc.SyncGlobalContext = true;
// When you update global time, all synced NPCs know
GlobalContextManager.Instance.SetTimeOfDay("dusk");See Context System for details.
Long-Term Memory
Make NPCs remember players across play sessions:
npc.EnableMemoryRetrieval = true; // Recall past conversationsWhen Long-Term Memory is turned on for your project, LoreMind stores new memories for requests that carry a playerId, which your backend adds from the player's verified login. LoreMind support turns Long-Term Memory on and records the memory agreement (your project's page in the LoreMind dashboard shows the status). It isn't available for projects marked Players under 18. While it's off, NPCs still answer, but no memories are stored or recalled. With EnableMemoryRetrieval off, the request neither reads nor stores memories.
Requires: Production setup with playerId provided in requests. See Long-Term Memory and Backend Integration.
Custom Transport (Advanced)
For advanced scenarios, you can override how requests are sent using custom transports.
SetTransport
Inject a custom transport implementation:
// Use a custom transport for this NPC
npc.SetTransport(myCustomTransport);If your game creates its transport in code, set Transport Mode to SetInCode in the Control Panel: the settings then create no transport, and the build check doesn't ask for a backend URL. Call SetTransport before the NPC's first request; in SetInCode mode an NPC without a transport answers with CONFIG_ERROR.
Transport Property
Access the current transport for debugging or logging:
var currentTransport = npc.Transport;
Debug.Log($"Using transport: {currentTransport.GetType().Name}");Transport Events
Monitor request/response flow for debugging. These are C# events on the transport itself (not UnityEvents on the component):
npc.Transport.OnRequestSending += request =>
{
Debug.Log($"Sending request: {request.text}");
};
npc.Transport.OnResponseReceived += response =>
{
Debug.Log($"Received response: {response.response}");
};
npc.Transport.OnTransportError += exception =>
{
Debug.LogError($"Transport error: {exception.Message}");
};OnTransportError fires only when sending throws; HTTP and network failures come back as responses.
Most developers won't need custom transports. The SDK automatically handles:
- Editor testing: uses your Server API Key stored locally (this transport doesn't exist in game client builds)
- Production builds: routes through your configured backend URL
See Backend Integration for production setup.
Monitoring Costs
Monitor credit usage and cost details in the LoreMind dashboard.
Cost-saving tips:
- Use
Terseverbosity for minor NPCs (configure in Entity Mind settings) - Clear conversation history when conversations end
- Only enable memory for NPCs where persistence matters
API Summary
The complete LoreMindNPC surface (every property, method, and event with signatures, types, and examples) is documented once in the SDK API Reference.
Next Steps
- Context System - Auto-detect locations and nearby entities
- Voice Input - Let players speak to NPCs
- Long-Term Memory - NPCs remember players across sessions
- API Reference - Complete API documentation