# Scripting API

The **Dialogue** scripting API lets you start, stop, and steer **[Scripts](../scripts.md)** from C#. Get a reference to a `Dialogue` component to control its conversation or wait for it to finish.

!!! info "The examples use existing references"
    Throughout this page, `this.m_Dialogue` is a `Dialogue` component, `this.m_Script` is a `Script` asset, and `this.m_Skin` is a `DialogueSkin` asset. The snippets omit namespace imports, and the surrounding `MonoBehaviour` already holds these fields.

## Dialogue

### Play a Script

`Play()` starts a conversation and returns an `Awaitable`, so your code can wait for the conversation to finish.

| Parameter    | Type           | Is                                                          |
| :--- | :--- | :--- |
| `script` | `Script`       | The `Script` asset to play.                                      |
| `target` | `GameObject`   | The game object that becomes **Target** for this execution.      |
| `skin`   | `DialogueSkin` | The UI skin to use for this execution. Pass `null` for no UI.    |

Await the result when later code depends on the conversation finishing:

```cs
public async Awaitable PlayAndWaitForCompletion()
{
    await this.m_Dialogue.Play(this.m_Script, this.gameObject, this.m_Skin);

    Debug.Log("Dialogue finished!");
}
```

`PlayAndWaitForCompletion` logs only after the Script finishes or the Dialogue is canceled. Put any work that depends on the conversation finishing after the `await`.

!!! tip "RunAsync starts without waiting"
    Calling `Play()` without `await` compiles with a warning and doesn't observe exceptions from the conversation.

    Call `RunAsync()` to start the conversation without blocking. It catches and logs exceptions:

    ```cs
    public void StartDialogueAndContinue()
    {
        this.m_Dialogue
            .Play(this.m_Script, this.gameObject, this.m_Skin)
            .RunAsync(this.gameObject);

        Debug.Log("Dialogue has been started.");
    }
    ```

    `StartDialogueAndContinue` logs immediately while the conversation continues. The `gameObject` passed to `RunAsync()` becomes the context for error messages, so use the object that started the conversation.

Without a `script` argument, `Play()` uses the component's **Script** field in the Inspector:

```cs
public async Awaitable PlayDefaultScript()
{
    await this.m_Dialogue.Play(this.gameObject, this.m_Skin);
}
```

Here, you can change which conversation runs by assigning a different asset in the Inspector.

### Cancel a conversation

`Cancel()` requests that a running conversation stop:

```cs
this.m_Dialogue.Cancel();
```

!!! warning "Canceling takes a frame"
    `Cancel()` marks the dialogue for termination; the cleanup happens on the next update.

    If your next operation needs the conversation to be fully stopped, wait a frame before running it.

### Advance the current line

`Continue()` performs the same action as the player pressing continue:

```cs
this.m_Dialogue.Continue();
```

!!! warning "The first Continue finishes an active text effect"
    The typewriter effect intercepts the call: the first `Continue()` finishes revealing the current line instead of moving on, and a second one is needed to advance.

    If your code calls it once while a text effect is running, the Dialogue remains on the current line.

### Pick a choice

`PickChoice()` selects an option while the conversation is waiting for player input.

| Parameter   | Type         | Is                                            |
| :--- | :--- | :--- |
| `index` | `int`        | The zero-based index of the choice to select. |
| `mode`  | `ChoiceMode` | Determines how the `index` is interpreted.    |

`ChoiceMode` determines which ordering the index uses:

| Value           | Indexes choices by                                    |
| :--- | :--- |
| `ScriptOrder`   | Their order in the `Script`.                          |
| `ShuffledOrder` | Their current on-screen order, which may be shuffled. |

When shuffling is on, the first choice in the Script may appear elsewhere on screen. Choose the ordering that matches where your index comes from.

Select the first choice as written in the Script with `ScriptOrder`:

```cs
public void PickFirstChoice()
{
    this.m_Dialogue.PickChoice(0, ChoiceMode.ScriptOrder);
}
```

The `0` selects the first Script entry even when the UI displays that entry elsewhere.

### Static events

Static events fire for every `Dialogue` in the game. Use them when one system must observe all conversations.

| Event         | Fires when                                                                               |
| :--- | :--- |
| `EventStart`  | Any `Dialogue` instance begins playing. The event passes that instance as a parameter.   |
| `EventFinish` | Any `Dialogue` instance finishes playing. The event passes that instance as a parameter. |

!!! example "Match every subscription with an unsubscribe"
    Subscribe in `OnEnable` and unsubscribe in `OnDisable` so the static event does not retain disabled or destroyed listeners:

    ```cs
    private void OnEnable()
    {
        Dialogue.EventStart += this.OnAnyDialogueStart;
    }

    private void OnDisable()
    {
        Dialogue.EventStart -= this.OnAnyDialogueStart;
    }

    private void OnAnyDialogueStart(Dialogue dialogue)
    {
        string dialogueName = dialogue.gameObject.name;
        Debug.Log($"A dialogue started on {dialogueName}");
    }
    ```

    `OnAnyDialogueStart` receives the component that started the conversation, so you can identify which game object it belongs to.

### Instance events

Instance events report detailed changes from one `Dialogue` component.

| Event                 | Fires when                             |
| :--- | :--- |
| `EventDialogueStart`  | This Dialogue starts playing.          |
| `EventDialogueFinish` | This Dialogue finishes.                |
| `EventTextStart`      | A new line of text is about to appear. |
| `EventTextFinish`     | The current line of text finishes.     |
| `EventChoiceStart`    | A set of choices appears.              |
| `EventChoicesFinish`  | The choice section finishes.           |
| `EventChoicesPick`    | The player picks a choice.             |
| `EventCommandStart`   | A Script command starts.               |
| `EventCommandFinish`  | A Script command finishes.             |

!!! example "Logging every line spoken anywhere"
    Static events identify when a conversation starts. Track each instance subscription so `OnDisable` can remove handlers from conversations that are still running:

    ```cs
    private readonly HashSet<Dialogue> m_ObservedDialogues = new HashSet<Dialogue>();

    private void OnEnable()
    {
        Dialogue.EventStart += this.OnAnyDialogueStart;
        Dialogue.EventFinish += this.OnAnyDialogueFinish;

        foreach (Dialogue dialogue in Dialogue.Active)
        {
            this.Observe(dialogue);
        }
    }

    private void OnDisable()
    {
        Dialogue.EventStart -= this.OnAnyDialogueStart;
        Dialogue.EventFinish -= this.OnAnyDialogueFinish;

        foreach (Dialogue dialogue in this.m_ObservedDialogues)
        {
            dialogue.EventTextStart -= this.OnTextStart;
        }

        this.m_ObservedDialogues.Clear();
    }

    private void OnAnyDialogueStart(Dialogue dialogue)
    {
        this.Observe(dialogue);
    }

    private void OnAnyDialogueFinish(Dialogue dialogue)
    {
        if (!this.m_ObservedDialogues.Remove(dialogue)) return;
        dialogue.EventTextStart -= this.OnTextStart;
    }

    private void Observe(Dialogue dialogue)
    {
        if (!this.m_ObservedDialogues.Add(dialogue)) return;
        dialogue.EventTextStart += this.OnTextStart;
    }

    private void OnTextStart(RuntimeScript runtimeScript, ScriptText scriptText)
    {
        Debug.Log(scriptText.GetText());
    }
    ```

    `OnAnyDialogueFinish` handles normal completion, while `OnDisable` removes subscriptions from Dialogues that are still active. Without both cleanup paths, a Dialogue can retain the handler after the observing component stops listening.

## Track active Dialogues

The static `Dialogue.Active` property is a `HashSet<Dialogue>` of every conversation currently playing in the scene.

!!! example "Cancel ambient dialogue before an important conversation"
    Cancel every active conversation, wait one frame for cleanup, then start the important conversation:

    ```cs
    public async Awaitable PlayImportantDialogue(Dialogue dialogue, DialogueSkin skin)
    {
        foreach (Dialogue activeDialogue in Dialogue.Active)
        {
            activeDialogue.Cancel();
        }

        await Awaitable.NextFrameAsync();

        await dialogue.Play(this.gameObject, skin);
    }
    ```

    The frame delay matters because `Cancel()` only marks a Dialogue for termination. Starting the new conversation before cleanup can leave the old one active for that frame.

## Where to go next

- **[Dialogue component](../dialogue.md)** — configure the component controlled by this API.
- **[Scripts](../scripts.md)** — define the content passed to `Play()`.
- **[Language syntax](../syntax.md)** — understand the lines reported by the text and choice events.
