> ## Documentation Index
> Fetch the complete documentation index at: https://docs.lokutor.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Unity: introduction

> Install the Lokutor package for Unity 2021.3+, add a Lokutor Agent to a character, and talk to it in five minutes: microphone, 3D voice, lip sync and game actions, with no other packages

> [!NOTE]
>
> Preview, version 0.2.0. Tell us what your game needs at [contact@lokutor.com](mailto:contact@lokutor.com).

The Lokutor package makes a character of your game a voice agent: it listens through the player's microphone, answers in its own voice from where it stands, moves its mouth, and calls your game's functions. It needs no other packages.

## What you need

* **Unity 2021.3** or newer, Mono or IL2CPP.
* A **Lokutor API key**, from [app.lokutor.com](https://app.lokutor.com).
* A microphone. Headphones while you try it, so the character does not hear itself.

It works on Windows, macOS, Linux, Android and iOS. WebGL is not supported yet (its builds have neither `System.Net.WebSockets` nor the `Microphone` class): for a web page use the [JavaScript SDK](https://docs.lokutor.com/guides/browser-setup.md).

## Install

**1. Add the package**

**Window > Package Manager > + > Add package from git URL**:

```
https://github.com/lokutor-ai/lokutor-sdk.git?path=/unity
```

**2. Ask for the microphone on mobile**

Add a microphone usage description (iOS: **Player Settings > Microphone Usage Description**).

## Your first character

**1. Add the component**

Select your character and **Add Component > Lokutor > Lokutor Agent**. It comes with an AudioSource, and the voice comes from where the GameObject is, so the head is a good place.

**2. Paste your API key**

In **Api Key**. Leave it empty to use `LokutorAgent.DefaultApiKey` or the `LOKUTOR_API_KEY` environment variable, which keeps the key out of your scenes. Never ship a game with a key inside: see [Shipping](#shipping).

**3. Say who it is**

Write **Persona**, and pick a **Voice** (`F1`-`F5`, `M1`-`M5`, or a voice from [your dashboard](https://docs.lokutor.com/voices-languages-models.md)) and a **Language**. `auto` follows the language the player speaks.

**4. Press Play and talk**

The character greets the player and listens.

Or import the **Talking blacksmith** sample (**Package Manager > Lokutor Voice Agents > Samples**): add its script to an empty GameObject, paste your key and press Play.

## Events

```csharp theme={null}
using Lokutor;
using UnityEngine;

public class Conversation : MonoBehaviour
{
    public LokutorAgent mira;
    public GameObject thinkingBubble;

    void Awake()
    {
        mira.onPlayerSaid.AddListener(text => Debug.Log("You: " + text));
        mira.onCharacterSaid.AddListener(text => Debug.Log("Mira: " + LokutorApi.StripTags(text)));
        mira.onStateChanged.AddListener(state => thinkingBubble.SetActive(state == AgentState.Thinking));
        mira.Error += error => Debug.LogWarning(error.Code + ": " + error.Message);
    }
}
```

`onCharacterSaid` carries what the character is about to say, with the [expression tags](https://docs.lokutor.com/api-reference/expression-tags.md) the voice performs (`[laugh]`); `LokutorApi.StripTags` takes them out.

| State | Meaning |
| :- | :- |
| `Disconnected` | No conversation. |
| `Connecting` | Opening it, or opening it again after the connection dropped. |
| `Ready` | Listening. |
| `PlayerTalking` | The player is talking. |
| `Thinking` | The player finished; the reply is being made. |
| `Speaking` | The character is being heard. |

## Start and stop

A conversation is billed while it is open ([Pricing](https://docs.lokutor.com/pricing.md)), so open it when the player engages. Turn off **Start On Awake** and:

```csharp theme={null}
void OnTriggerEnter(Collider other) { if (other.CompareTag("Player")) mira.StartConversation(); }

void OnTriggerExit(Collider other) { if (other.CompareTag("Player")) mira.StopConversation(); }
```

While it is open you can change who the character is and what it knows:

```csharp theme={null}
mira.SetPersona("You are Mira. The player just insulted you and you want an apology.");
mira.SetContext("Gold the player has", "12");     // facts of the moment; null takes one out
mira.SetVoice("F3");
mira.SetLanguage("es");
mira.ResetConversation();                          // it forgets what was said
```

When the connection drops it is opened again by itself (`onReconnecting`, then `onReconnected`). The new session does not remember the old one: the facts of `SetContext` are sent again, what was said is not. If it cannot be opened, or the server ends it, `onConversationEnded` says why.

## Microphone

| `micMode` | |
| :- | :- |
| `Always` (default) | The microphone is open; the server notices when the player stops talking. |
| `PushToTalk` | Heard only while **Push To Talk Key** (old Input Manager) or **Push To Talk Action** (Input System) is held, or between `SetTalking(true)` and `SetTalking(false)`. |
| `Off` | No microphone. The character hears what you give `FeedMicrophone(samples, offset, count, rate)`: a recording, or another character's `VoicePlayed`. Send silence too when there is nothing to hear. |

**Mute Mic While Speaking** (on) sends silence while the character's voice can still reach the microphone, so laptop speakers do not make it interrupt itself, and while another character or a `LokutorVoice` is heard, so that it does not answer them. Turn it off when players wear headphones and you want them to be able to interrupt. `Muted = true` is the player's own mute button. **Microphone Device** picks another microphone.

## The voice

It plays through the AudioSource: its mixer group, distances and effects are yours. **Spatial Voice** places it in 3D; **Pitch** shifts it up or down.

## A dashboard agent

To use an agent built in the [dashboard](https://docs.lokutor.com/guides/my-first-agent.md) (prompt, voice, knowledge, tools), set **Agent Id** and empty **Persona**, **Voice** and **Language**: whatever you leave in them overrides the dashboard. `SetContext` needs a persona in the game, because a dashboard prompt cannot be extended from it.

## Shipping

A key inside a game build can be extracted. Have your server trade it for a ticket that lasts ten minutes ([`POST /ws-ticket`](https://docs.lokutor.com/guides/secure-browser-setup)) and give the agent that. `TicketProvider` is called on the main thread before every connection, reconnections included:

```csharp theme={null}
using System;
using System.Threading.Tasks;
using Lokutor;
using UnityEngine;
using UnityEngine.Networking;

public class Tickets : MonoBehaviour
{
    [Serializable] class Reply { public string ticket; }

    void Awake() => GetComponent<LokutorAgent>().TicketProvider = GetTicket;

    async Task<string> GetTicket()
    {
        using (var request = new UnityWebRequest("https://your-server.example/lokutor-ticket", "POST"))
        {
            request.downloadHandler = new DownloadHandlerBuffer();
            var sent = request.SendWebRequest();
            while (!sent.isDone) await Task.Yield();
            return request.result == UnityWebRequest.Result.Success ? JsonUtility.FromJson<Reply>(request.downloadHandler.text).ticket : "";
        }
    }
}
```

Return an empty string when there is no ticket: the conversation ends with an error instead of waiting. The same property exists on [LokutorVoice](https://docs.lokutor.com/sdks/unity/speech.md).

## Next

* [Actions](https://docs.lokutor.com/sdks/unity/actions.md): let the character do things in the game.
* [Lip sync](https://docs.lokutor.com/sdks/unity/lip-sync.md): blend shapes, jaws, 2D mouths.
* [Speech](https://docs.lokutor.com/sdks/unity/speech.md): written lines, text to speech and speech to text.
* [API reference](https://docs.lokutor.com/sdks/unity/reference.md): every type and member.
* [Game characters](https://docs.lokutor.com/guides/game-characters.md): what makes one feel alive.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.