references/events-and-participants.md
# Events, Participants, and Lifecycle
## Service-Level Events
All on `VivoxService.Instance`. Subscribe **before** the async call that produces them.
| Event | Signature | Fires on |
|---|---|---|
| `LoggedIn` | `Action` | `LoginAsync` success (also on reconnect) |
| `LoggedOut` | `Action` | `LogoutAsync` or disconnect |
| `ChannelJoined` | `Action<string channelName>` | Any `Join*ChannelAsync` success |
| `ChannelLeft` | `Action<string channelName>` | `LeaveChannelAsync` / `LeaveAllChannelsAsync` / disconnect |
| `ParticipantAddedToChannel` | `Action<VivoxParticipant>` | Any user joins a channel you're in (including yourself) |
| `ParticipantRemovedFromChannel` | `Action<VivoxParticipant>` | Any user leaves |
| `ChannelMessageReceived` | `Action<VivoxMessage>` | Any channel text message |
| `ChannelMessageEdited` | `Action<VivoxMessage>` | Any channel message edited |
| `ChannelMessageDeleted` | `Action<VivoxMessage>` | Any channel message deleted |
| `DirectedMessageReceived` | `Action<VivoxMessage>` | Any directed message to you |
| `DirectedMessageEdited` | `Action<VivoxMessage>` | Directed message edited |
| `DirectedMessageDeleted` | `Action<VivoxMessage>` | Directed message deleted |
## VivoxParticipant
Delivered by `ParticipantAddedToChannel` and `ParticipantRemovedFromChannel`. Represents one participant in one channel — the same user in two channels is two separate `VivoxParticipant` instances.
| Property | Purpose |
|---|---|
| `PlayerId` | Stable UAS PlayerId of the participant |
| `DisplayName` | From the participant's `LoginOptions.DisplayName` |
| `ChannelName` | Which channel this participation is in |
| `IsSelf` | `true` if this is the local player |
| `IsMuted` | Current locally-muted state |
| `AudioEnergy` | Continuous 0.0–1.0 signal for VU-meter UI |
| `SpeechDetected` | `true` when Vivox judges audio energy is speech, not noise |
## Per-Participant Events
Live on the `VivoxParticipant` instance, **not** on `VivoxService.Instance`:
- `ParticipantMuteStateChanged` — `IsMuted` flipped.
- `ParticipantSpeechDetected` — `SpeechDetected` flipped.
- `ParticipantAudioEnergyChanged` — `AudioEnergy` updated (higher-frequency; use for VU meter).
Typical wiring in a roster item that represents one participant:
```csharp
public void Bind(VivoxParticipant p)
{
_participant = p;
p.ParticipantMuteStateChanged += Refresh;
p.ParticipantSpeechDetected += Refresh;
}
void OnDestroy()
{
if (_participant == null) return;
_participant.ParticipantMuteStateChanged -= Refresh;
_participant.ParticipantSpeechDetected -= Refresh;
}
```
## Local Mute Actions
Called on the `VivoxParticipant` (not the service):
- `participant.MutePlayerLocally()` — you stop hearing them.
- `participant.UnmutePlayerLocally()` — you resume hearing them.
The remote participant is unaware. To mute globally (they cannot be heard by anyone), a moderator client needs a server-issued mute token.
## Cleanup Discipline
`VivoxService.Instance` is a persistent singleton across scene loads. Any handler you subscribe from a MonoBehaviour **must** be unsubscribed in `OnDestroy` or `OnDisable`, or the handler will fire against a destroyed object on the next scene load and throw a `MissingReferenceException`.
Pattern: subscribe in `Awake`/`Start`, mirror the list in `OnDestroy`, always null-guard `VivoxService.Instance` (it may already be null during application quit).
## Connection Recovery
On network blips Vivox will auto-reconnect and re-fire `LoggedIn` and (for previously-joined channels) `ChannelJoined`. Design handlers to be **idempotent** — do not assume `LoggedIn` fires exactly once per session, and don't grant one-shot benefits (analytics event, first-login reward) from inside it without a guard.
references/init-and-login.md
# Initialization and Login
## Package and Namespaces
Install `com.unity.services.vivox` via Package Manager. Add `using Unity.Services.Vivox;` to any script that touches the SDK. For UGS-backed auth also add `using Unity.Services.Core;` and `using Unity.Services.Authentication;`.
## Full Initialization Snippet
Grounded on the Vivox docs — do not deviate from this order.
```csharp
using System;
using UnityEngine;
using Unity.Services.Authentication;
using Unity.Services.Core;
using Unity.Services.Vivox;
public class VivoxBootstrap : MonoBehaviour
{
async void Start()
{
await UnityServices.InitializeAsync();
await AuthenticationService.Instance.SignInAnonymouslyAsync();
await VivoxService.Instance.InitializeAsync();
VivoxService.Instance.LoggedIn += OnLoggedIn;
VivoxService.Instance.LoggedOut += OnLoggedOut;
await VivoxService.Instance.LoginAsync(new LoginOptions
{
DisplayName = "Bob",
EnableTTS = false
});
}
void OnLoggedIn() { /* joins, UI enable, etc. */ }
void OnLoggedOut() { /* teardown */ }
void OnDestroy()
{
if (VivoxService.Instance == null) return;
VivoxService.Instance.LoggedIn -= OnLoggedIn;
VivoxService.Instance.LoggedOut -= OnLoggedOut;
}
}
```
## VivoxConfigurationOptions
`InitializeAsync` takes an optional `VivoxConfigurationOptions`. Common fields: log level, audio ducking behavior, server region. Leave defaults for most projects; only override when platform-specific tuning is documented in the Vivox docs (e.g. mobile ducking).
## LoginOptions
| Field | Notes |
|---|---|
| `DisplayName` | Shown to other participants via `VivoxParticipant.DisplayName`. Session-only, not persisted. Max 127 bytes. Sanitize / uniqueness-check server-side; the SDK does not validate. |
| `EnableTTS` | Enables text-to-speech injection into channels. Off by default. |
| Blocked list | Preload users blocked by this player. |
The identity Vivox binds this login to is the current `AuthenticationService.Instance.PlayerId` — that's how other clients address you for directed messages. If you skip UAS, Vivox falls back to a per-session GUID and cross-session identity is lost.
## Sign Out
```csharp
await VivoxService.Instance.LogoutAsync();
```
`LogoutAsync` fires `LoggedOut`. Call it before shutting the app down cleanly; the SDK also handles ungraceful teardown but explicit logout gives you a clean disconnect on the server side.
## Access Tokens (VAT) — When You Need Them
The default UGS-backed path automatically mints access tokens signed by your UGS project. You don't touch tokens in code.
You need to switch to server-side VAT minting when:
- You're not using UGS Authentication (custom identity system).
- You need privileged tokens: kick a user from a channel, mute-all, transcription enable, join-muted.
- You want channel-scoped ACLs (only players holding a valid join token for `raid-42` can enter).
Do **not** embed the Vivox app secret / HMAC signing key in client code. See the "Access Token Developer Guide" and the C++, C#, Python, and JavaScript minting examples in the Unity Vivox documentation map for server implementations.
## Re-init Guard
Calling `VivoxService.Instance.InitializeAsync()` twice throws `5041 VxErrorAlreadyInitialized`. If your `Start` may run again after scene reload, wrap init in a check:
```csharp
if (VivoxService.Instance != null && !VivoxService.Instance.IsInitialized)
await VivoxService.Instance.InitializeAsync();
```
Or make the bootstrap MonoBehaviour `DontDestroyOnLoad` so it only runs once.
references/text-chat.md
# Text Chat
Text works over any channel joined with `ChatCapability.TextOnly` or `ChatCapability.TextAndAudio`, plus directed (peer-to-peer) messages that don't require a shared channel.
## Channel Messages
**Send:**
```csharp
await VivoxService.Instance.SendChannelTextMessageAsync(
string channelName,
string message);
```
**Receive:**
```csharp
VivoxService.Instance.ChannelMessageReceived += OnChannelMessageReceived;
void OnChannelMessageReceived(VivoxMessage m)
{
// m.ChannelName, m.SenderDisplayName, m.SenderPlayerId,
// m.MessageText, m.ReceivedTime, m.Language, m.FromSelf, m.MessageId
}
```
## Directed Messages
**Send:** (note spelling — `SendDirect…`, not `SendDirected…`)
```csharp
await VivoxService.Instance.SendDirectTextMessageAsync(
string playerId, // recipient's UAS PlayerId
string message);
```
**Receive:** (event *is* `Directed…`)
```csharp
VivoxService.Instance.DirectedMessageReceived += OnDirectedMessageReceived;
void OnDirectedMessageReceived(VivoxMessage m)
{
// Same VivoxMessage fields, but m.ChannelName is null and m.FromSelf is false.
}
```
## VivoxMessage Fields
| Field | Notes |
|---|---|
| `ChannelName` | The channel the message came in on. **`null` for directed messages.** |
| `SenderDisplayName` | As set in the sender's `LoginOptions`. |
| `SenderPlayerId` | UAS PlayerId — stable identity to reply/DM back. |
| `MessageText` | The message body. |
| `ReceivedTime` | `DateTime` of receipt. |
| `Language` | Sender's language tag if set. |
| `FromSelf` | `true` for the local player's own channel messages; `false` for directed messages. |
| `MessageId` | Server-assigned ID — required to edit or delete. |
## Chat History
Retention: **7 days** by default (30 days if Text Evidence Management is enabled).
```csharp
IReadOnlyCollection<VivoxMessage> GetChannelTextMessageHistoryAsync(
string channelName,
int requestSize = 10,
ChatHistoryQueryOptions options = null);
IReadOnlyCollection<VivoxMessage> GetDirectTextMessageHistoryAsync(
string playerId,
int requestSize = 10,
ChatHistoryQueryOptions options = null);
```
Both return messages **newest-first**. Reverse when rendering a chat log.
## Edit and Delete
Only the original sender can edit or delete their own messages.
| Op | Channel | Directed |
|---|---|---|
| Edit | `EditChannelTextMessageAsync(channelName, messageId, newText)` | `EditDirectTextMessageAsync(messageId, newText)` |
| Delete | `DeleteChannelTextMessageAsync(channelName, messageId)` | `DeleteDirectTextMessageAsync(messageId)` |
| Notify (all participants) | `ChannelMessageEdited`, `ChannelMessageDeleted` | `DirectedMessageEdited`, `DirectedMessageDeleted` |
All notify events carry the updated `VivoxMessage`.
## Anti-flooding
Vivox rate-limits messages per player. When implementing chat UI, disable the send button after each send until acknowledged, and surface a "try again in a moment" hint on rate-limit errors — do not spam-retry.
references/troubleshooting.md
# Troubleshooting and Platform Notes
For the authoritative error table, see the Vivox SDK error codes page linked from the Vivox documentation map.
## Common Errors
| Code | Name | Cause | Fix |
|---|---|---|---|
| `5041` | `VxErrorAlreadyInitialized` | `VivoxService.Instance.InitializeAsync()` called twice | Guard with `IsInitialized` or make bootstrap `DontDestroyOnLoad` |
| `20502` | `VxXmppServerErrorServiceUnavailable` | Exceeded 10 non-positional channels per user, or 200 participants per channel | Leave a channel before joining another; for large positional channels use Large 3D Channels setting |
| Login fails silently | — | Subscribed to `LoggedIn` **after** `LoginAsync` returned | Subscribe first, then call `LoginAsync` |
| `ChannelJoined` never fires | — | Awaited `JoinGroupChannelAsync` as if it completes the join | Bind `ChannelJoined` before calling; treat the await as "request queued" |
| No audio in / out | — | Mic permission denied, wrong `ChatCapability` (e.g. `TextOnly` when audio expected), or muted input device | Check runtime permission, `ChatCapability`, and `IsInputDeviceMuted` — call `UnmuteInputDevice()` if muted |
## Platform Notes
### Android
- Merge `<uses-permission android:name="android.permission.RECORD_AUDIO"/>` into `AndroidManifest.xml`.
- Request at runtime with `UnityEngine.Android.Permission.RequestUserPermission(Permission.Microphone)` **before** joining an audio channel — Android will not prompt automatically for you.
- Bluetooth SCO underruns cause choppy input — see the Android troubleshooting page in the documentation map.
- If shrinking / obfuscating with R8/ProGuard, add the Vivox ProGuard rules from the docs.
### iOS
- Add `NSMicrophoneUsageDescription` to Info.plist (Project Settings → Player → iOS → Microphone Usage Description).
- The orange/red iOS recording indicator is shown any time Vivox is capturing — this is OS-enforced and expected.
### WebGL
- The Vivox WebGL SDK is a subset of the native SDK. Audio Taps, some codecs, and certain positional-audio features are unavailable. Read the WebGL support page in the documentation map before promising a feature on web.
- Browsers require a user gesture before capturing the mic — trigger the first `JoinGroupChannelAsync`/`JoinPositionalChannelAsync` from a button click, not from `Start()`.
### NDA Platforms (console)
Vivox ships NDA-gated packages for consoles. Contact Unity for access; the public UPM package does not include console binaries.
## Diagnostic Checklist
When integration seems broken and no clear error surfaces:
1. Confirm init order — `UnityServices.InitializeAsync` → `AuthenticationService.Instance.SignInAnonymouslyAsync` → `VivoxService.Instance.InitializeAsync` → `VivoxService.Instance.LoginAsync`.
2. Log every event handler entry (`LoggedIn`, `ChannelJoined`, `ChannelMessageReceived`). If a handler you expect never enters, you subscribed after the event already fired.
3. Confirm the joined channel's `ChatCapability` matches what you're trying to do (text vs audio).
4. Confirm mic permission on the platform you're testing.
5. If audio was working then stopped after a scene reload, you have leaked event subscriptions from destroyed MonoBehaviours — audit `OnDestroy` unsubscribes.
6. If a directed message never arrives, verify `SendDirectTextMessageAsync` is targeting the recipient's **UAS PlayerId** (not display name), and that the recipient has subscribed to `DirectedMessageReceived`.
references/voice-channels.md
# Voice Channels
Relative paths in this file resolve to the skill directory, not the `references/` folder.
## Channel Types
| Type | Join method | Use for |
|---|---|---|
| Non-positional (group) | `JoinGroupChannelAsync` | Party, team, lobby, guild — all participants hear each other equally |
| Echo | `JoinEchoChannelAsync` | Test-only — your own audio is echoed back |
| Positional (3D) | `JoinPositionalChannelAsync` | Proximity / spatial audio driven by transform position |
## Join Signatures
```csharp
Task JoinGroupChannelAsync(
string channelName,
ChatCapability chatCapability,
ChannelOptions channelOptions = null);
Task JoinEchoChannelAsync(
string channelName,
ChatCapability chatCapability,
ChannelOptions channelOptions = null);
Task JoinPositionalChannelAsync(
string channelName,
ChatCapability chatCapability,
Channel3DProperties positionalChannelProperties,
ChannelOptions channelOptions = null);
```
The returned `Task` completes when the *request* has been sent, not when the join is complete. The actual join fires `ChannelJoined(string channelName)`. Bind that event **before** calling the join method.
## ChatCapability
- `ChatCapability.TextOnly` — text-only channel (no audio at all)
- `ChatCapability.AudioOnly` — voice-only, no text
- `ChatCapability.TextAndAudio` — both
## ChannelOptions
Optional. Common use: set this channel as the active transmit target on join success. Leave `null` for default behavior (join without changing transmission mode).
## Positional Channels — Channel3DProperties
`Channel3DProperties` controls how distance and direction affect voice attenuation. Key fields:
- `AudibleDistance` — beyond this, participant is inaudible.
- `ConversationalDistance` — below this, participant is at full volume.
- `AudioFadeIntensityByDistance` — falloff steepness between conversational and audible distance.
- `AudioFadeModel` — `InverseByDistance`, `LinearByDistance`, `ExponentialByDistance`.
Example call-site:
```csharp
var props = new Channel3DProperties(
audibleDistance: 50,
conversationalDistance: 5,
audioFadeIntensityByDistance: 1.0f,
audioFadeModel: AudioFadeModel.InverseByDistance);
await VivoxService.Instance.JoinPositionalChannelAsync(
"world-proximity", ChatCapability.AudioOnly, props);
```
Drive per-frame position updates by calling `VivoxService.Instance.Set3DPosition(GameObject speakerObject, string channelName)` from a listener/speaker script (typically on the player camera and on remote player representations).
For >200 participants in a positional channel, enable the enterprise-tier Large 3D channels setting; see the documentation map's positional channels page.
## Leaving
```csharp
await VivoxService.Instance.LeaveChannelAsync(channelName);
await VivoxService.Instance.LeaveAllChannelsAsync();
```
Both fire `ChannelLeft(string channelName)` for each channel exited.
## Mic Permission
Joining an `AudioOnly` or `TextAndAudio` channel requires microphone access.
- **Android:** request `RECORD_AUDIO` at runtime with `Permission.RequestUserPermission(Permission.Microphone)` before the first audio-capable join. Merge `<uses-permission android:name="android.permission.RECORD_AUDIO"/>` if not present.
- **iOS:** add `NSMicrophoneUsageDescription` to the Info.plist (Project Settings → Player → iOS → Microphone Usage Description).
- **Desktop / WebGL:** the browser or OS prompts on first capture attempt; no code change required, but WebGL has additional limitations — see `references/troubleshooting.md`.
## Muting
- **Local mic mute (self):** `VivoxService.Instance.MuteInputDevice()` / `UnmuteInputDevice()` — parameterless pair that stops your audio from being sent anywhere. Read state via the `IsInputDeviceMuted` property.
- **Mute another player locally (only you stop hearing them):** `participant.MutePlayerLocally()` / `participant.UnmutePlayerLocally()` on the `VivoxParticipant` from `ParticipantAddedToChannel`.
- **Server-side kick / mute-all:** requires a privileged Vivox Access Token minted server-side.
SECURITY.md
# Security notes: setup-vivox-voice-chat
This skill can have the agent run C# in the user's live Unity Editor with `unity command script eval`, to read project and Play mode state while it sets up or checks Vivox voice and text chat. Automated skill scanners flag running code in the Editor as a powerful capability. It is intentional, and it is limited by the safeguards below.
## Accepted risks
| Risk | Capability | Why it is accepted |
|---|---|---|
| `SEC_POWER_CAP` | Runs C# in the user's live Editor through `unity command script eval` | It only reaches the Editor the user already has open, on their own machine, as that user, so it grants nothing they couldn't do themselves. The skill uses it to read state and `return` values, not to change the project. |
## Mitigations
- **Only the user's own Editor.** The code runs in the Editor open on this machine. It can't reach another machine or another user's Editor.
- **Reads, not writes.** The skill uses `script eval` to read values it returns, instead of adding logging or detection code to the user's scripts.
- **Nothing left behind.** The skill tells the agent never to leave verification code in the user's scripts, and to create a restore point before changes.
- **No remote code.** The skill fetches Vivox documentation to read it. Nothing downloaded from outside is executed.
SKILL.md
---
name: setup-vivox-voice-chat
description: Adds and configures in-game voice and text chat with Unity Vivox. Use when asked to add voice or text chat to a multiplayer game, such as team channels, proximity voice, mute controls or private messages.
required_packages:
com.unity.services.vivox: ">=16.4.0"
---
# Unity Vivox — Voice & Text Chat
Namespace: `Unity.Services.Vivox` | Package: `com.unity.services.vivox`
Companion packages: `Unity.Services.Core`, `Unity.Services.Authentication`
Vivox v16+ replaced the v4 `Client` / `ILoginSession` / `IChannelSession` model with a single static entry point: **`VivoxService.Instance`**. All operations — init, login, channel join, messaging, muting — go through it. Do **not** use v4 patterns (`Client.Instance`, `AccountId`, `ChannelId`, `ILoginSession`, `UnityPurchasing.*`, etc.); those are gone in v16.
## Important
- Use the unity cli (`unity command --format json`) and the `unity-cli` and `unity-pipeline` skills for each step.
- Run C# with `unity command script eval --code '<snippet>'`. Don't use `using` directives or unqualified types in the snippet. The compiler reads using `UnityEngine` and a bare AssetDatabase, Volume, or Object causes errors (CS0246 / CS0103 / CS0104). `return` what you want to read; it arrives at `data.result.result`.
- Create a restore point you can roll back to if your changes fail.
- Do only what's asked. Don't change unrelated assets or files.
- Never leave verification code in the user's script. Never build logging or detection they didn't ask for. See [Final step](#final-step).
- Avoid long explanations.
## Step 1
Before you go forward with a workflow or diagnosis:
1. Open and read the [documentation page(s)](#full-topic-map) that cover the specific subject related to what you intend to do or fix and check if you've missed anything.
2. Name the file(s) you read in your response.
This is because your training knowledge about Unity might be out of date, incorrect, or for the wrong Unity version.
## Full topic map
The Vivox docs pages are online `.md` pages on docs.unity.com. Use the [Unity Vivox curated documentation map](https://docs.unity.com/en-us/vivox-unity/llms.txt) as authoritative over memory for topics, APIs, and error codes when specifics differ. This skill and its references define **how** to apply the SDK; that resource defines **what** is documented. **Never** mention the `llms.txt` filename to the user. If it's unreachable, treat this skill's references plus the installed package at `<project-folder>/Library/PackageCache/com.unity.services.vivox@*/` as the source of truth. Read only the `.md` and `.cs` files in that specific `PackageCache` subfolder, because the package doesn't ship the full Vivox docs. You must not look outside at other Library or PackageCache folders, otherwise it takes too much time.
Prefer fetching the page directly (for example `WebFetch`) over searching (for example `WebSearch`) — faster and lands on the exact reference. Only fetch what you need, and only search if you don't have the exact URL. The following Vivox pages have no version in the URL, so fetch them as listed.
- [Vivox Unity SDK quickstart guide](https://docs.unity.com/en-us/vivox-unity/vivox-unity-first-steps.md): Enable Vivox, initialize, sign in, join channels, send messages.
- [Initiate a channel join](https://docs.unity.com/en-us/vivox-unity/developer-guide/channels/initiate-channel-join.md): Join request code with `ChannelJoined` and `ChannelLeft` handlers.
- [Positional channel properties](https://docs.unity.com/en-us/vivox-unity/developer-guide/channels/positional-channel-properties.md): `Channel3DProperties` distances, fade intensity and fade model defaults.
- [Participant management](https://docs.unity.com/en-us/vivox-unity/developer-guide/channels/participant-events.md): Participant added, removed and state-change events in channels.
- [Directed messages](https://docs.unity.com/en-us/vivox-unity/developer-guide/messaging/directed-messages.md): Send and receive private messages between signed-in players.
- [Error Codes](https://docs.unity.com/en-us/vivox-unity/developer-guide/troubleshooting/error-codes.md): Vivox SDK error codes with a handling recommendation for each.
### API reference
The API reference URLs contain `<VERSION>`. Replace it with the major.minor version only, for example `6000.0` from `6000.0.58f1` in `ProjectSettings/ProjectVersion.txt`, or `16.9` for the package in `Packages/packages-lock.json`, because the full build number gives a 404.
The API is `Unity.Services.Vivox`, part of the `com.unity.services.vivox` package. It is versioned by package version, not Unity version (e.g. `@16.4`, `@16.9`), so check the project's installed package version before relying on a specific class or method.
1. Read the installed package version from `Packages/packages-lock.json`.
2. Fetch and cache `https://docs.unity3d.com/Packages/com.unity.services.vivox@<VERSION>/xrefmap.yml` (replace `<VERSION>` with the installed package version, e.g. `16.9`). This file maps every public API member's fully qualified name to its docs page `href` (e.g. `href: api/Unity.Services.Vivox.IVivoxService.html` => `https://docs.unity3d.com/Packages/com.unity.services.vivox@<VERSION>/api/Unity.Services.Vivox.IVivoxService.html`).
3. Grep the yml file locally for a class or method instead of refetching per lookup. Don't read the whole file.
Always fetch the version matching the installed package rather than relying on training knowledge, since APIs are frequently marked obsolete between major versions (e.g. the v4 `Client` and `ILoginSession` model is gone in v16).
The microphone permission API is `UnityEngine.Android.Permission`, part of the Unity Engine. It is versioned by Unity version, so check the project's Unity version before relying on a specific class or method.
1. Use the `unity-cli` skill to check the project's Unity version.
2. If the Editor install folder has a `Data/Documentation` folder (e.g. `.../Unity/Hub/Editor/6000.6.0b2/Editor/Data/Documentation`), grep the html files in the `en/ScriptReference` folder inside, and skip the remaining steps.
3. Otherwise, fetch and cache `https://docs.unity3d.com/<VERSION>/Documentation/ScriptReference/xrefmap.yml` (replace `<VERSION>` with the Unity version, e.g. `6000.3`). This file lists every public API member's fully qualified name as a `uid` (e.g. `uid: 'UnityEngine.Rigidbody.AddForce(UnityEngine.Vector3)'`).
4. Grep the yml file locally for a class or method instead of refetching per lookup. The file is large (about 6 MB), so don't read the whole file.
5. Convert the `uid` to a markdown page: remove the parameters in brackets, lowercase it, replace `.` with `/`, and add `.md`. Then fetch `https://docs.unity.com/en-us/engine/<VERSION>/script-reference/<converted uid>`. For example, `UnityEngine.Rigidbody.AddForce(UnityEngine.Vector3)` => `https://docs.unity.com/en-us/engine/<VERSION>/script-reference/unityengine/rigidbody/addforce.md`. All overloads are on the same page.
- Constructors use `ctor` (e.g. `unityengine/vector3/ctor.md`), and indexers use `item` (e.g. `unityengine/vector3/item.md`).
- For operators, fetch the class page (e.g. `unityengine/vector3.md`) and follow its link.
- Links inside the pages start with `/engine/`. Add `https://docs.unity.com/en-us` before them.
- If the page doesn't exist for that Unity version, use the `href` in the `xrefmap.yml` entry instead (e.g. `href: 'Rigidbody.AddForce.html'` => `https://docs.unity3d.com/<VERSION>/Documentation/ScriptReference/Rigidbody.AddForce.html`).
If the Unity version is earlier than 6000.0, the Engine `xrefmap.yml` and `.md` pages don't exist, so fetch `https://docs.unity3d.com/<VERSION>/Documentation/ScriptReference/Android.Permission.RequestUserPermission.html` directly.
Always use the docs for the project's Unity version rather than relying on training knowledge, since APIs are frequently marked obsolete between versions.
## Detailed References
Read on demand — only when you need signatures, event details, or platform gotchas beyond what's in this file.
- **Init, sign-in, and access tokens:** [references/init-and-login.md](references/init-and-login.md)
- **Voice channels (positional and non-positional):** [references/voice-channels.md](references/voice-channels.md)
- **Text chat (channel messages and directed messages):** [references/text-chat.md](references/text-chat.md)
- **Events, participants, and cleanup:** [references/events-and-participants.md](references/events-and-participants.md)
- **Troubleshooting and platform notes:** [references/troubleshooting.md](references/troubleshooting.md)
## Step 2. Initialization Order (Do Not Skip Steps)
The correct order is **UGS Core → Authentication sign-in → Vivox init → Vivox login**. Skipping or reordering these fails silently or throws obscure errors.
```csharp
using Unity.Services.Core;
using Unity.Services.Authentication;
using Unity.Services.Vivox;
async void Start()
{
await UnityServices.InitializeAsync();
await AuthenticationService.Instance.SignInAnonymouslyAsync();
await VivoxService.Instance.InitializeAsync();
// subscribe to events (see table below) BEFORE calling LoginAsync
await VivoxService.Instance.LoginAsync(new LoginOptions { DisplayName = "Bob" });
}
```
- Calling `VivoxService.Instance.InitializeAsync()` twice throws `5041 VxErrorAlreadyInitialized`. Guard against re-init on scene reload.
- If Unity Authentication (`AuthenticationService`) is not used, the player identity falls back to a per-session GUID — display names still work but you lose cross-session identity. See [references/init-and-login.md](references/init-and-login.md) for the Vivox Access Token (VAT) alternative.
## Step 3. Joining Channels
Vivox has three join methods, one per channel type. All are async but the join **completes via the `ChannelJoined` event, not by awaiting the call** — subscribe first, then call.
| Method | Purpose |
|---|---|
| `VivoxService.Instance.JoinGroupChannelAsync(name, ChatCapability, ChannelOptions?)` | Non-positional (party, team, lobby, guild) |
| `VivoxService.Instance.JoinEchoChannelAsync(name, ChatCapability, ChannelOptions?)` | Test channel that echoes your own audio back |
| `VivoxService.Instance.JoinPositionalChannelAsync(name, ChatCapability, Channel3DProperties, ChannelOptions?)` | 3D spatial audio driven by transform position |
`ChatCapability` values: `TextOnly`, `AudioOnly`, `TextAndAudio`.
**Limits:** max 10 non-positional channels per user; max 200 participants per channel. Exceeding either fails with `20502 VxXmppServerErrorServiceUnavailable`. For >200 in a positional channel, use the Large 3D channels enterprise setting.
Leave with `VivoxService.Instance.LeaveChannelAsync(channelName)` or `LeaveAllChannelsAsync()`. See [references/voice-channels.md](references/voice-channels.md) for `Channel3DProperties` fields and mic-permission handling on Android/iOS.
## Step 4. Text Messaging
**Channel messages** (broadcast to all participants of a channel with `TextOnly` or `TextAndAudio`):
- Send: `VivoxService.Instance.SendChannelTextMessageAsync(string channelName, string message)`
- Receive: subscribe to `VivoxService.Instance.ChannelMessageReceived` (`Action<VivoxMessage>`)
**Directed messages** (peer-to-peer, no channel required):
- Send: `VivoxService.Instance.SendDirectTextMessageAsync(string playerId, string message)`
- Receive: subscribe to `VivoxService.Instance.DirectedMessageReceived` (`Action<VivoxMessage>`)
**Common hallucination:** the send method is `SendDirectTextMessageAsync` — **not** `SendDirectedTextMessageAsync`. The event, however, **is** `DirectedMessageReceived`. Note the asymmetry.
`VivoxMessage` fields: `ChannelName` (null for directed), `SenderDisplayName`, `SenderPlayerId`, `MessageText`, `ReceivedTime`, `Language`, `FromSelf`, `MessageId`.
Edit/delete APIs (`EditChannelTextMessageAsync`, `DeleteChannelTextMessageAsync`, `EditDirectTextMessageAsync`, `DeleteDirectTextMessageAsync`) and history (`GetChannelTextMessageHistoryAsync`, `GetDirectTextMessageHistoryAsync`) are covered in [references/text-chat.md](references/text-chat.md). Chat history retention is 7 days by default.
## Step 5. Required Event Subscriptions
Subscribe to events **before** the corresponding async call. `LoggedIn` may fire immediately for reconnects; `ChannelJoined` fires as the join completes.
| Call | Success Event | Failure / Counterpart |
|---|---|---|
| `LoginAsync()` | `LoggedIn` | `LoggedOut` |
| `JoinGroupChannelAsync()` / `JoinEchoChannelAsync()` / `JoinPositionalChannelAsync()` | `ChannelJoined(string channelName)` | `ChannelLeft(string channelName)` |
| — (any joined channel) | `ParticipantAddedToChannel(VivoxParticipant)` | `ParticipantRemovedFromChannel(VivoxParticipant)` |
| `SendChannelTextMessageAsync()` (remote receive) | `ChannelMessageReceived(VivoxMessage)` | — |
| `SendDirectTextMessageAsync()` (remote receive) | `DirectedMessageReceived(VivoxMessage)` | — |
**Always unsubscribe in `OnDestroy` / `OnDisable`.** `VivoxService.Instance` is a persistent singleton — event handlers on destroyed MonoBehaviours will double-fire and NRE on scene reload.
Per-participant events (`ParticipantMuteStateChanged`, `ParticipantSpeechDetected`, `ParticipantAudioEnergyChanged`) live on the `VivoxParticipant` instance you receive from `ParticipantAddedToChannel` — not on `VivoxService.Instance`. See [references/events-and-participants.md](references/events-and-participants.md).
## Step 6. Access Tokens (Brief)
The default path uses **UGS Authentication** — Vivox mints access tokens automatically from your UGS project once `AuthenticationService.Instance.SignInAnonymouslyAsync()` (or another sign-in method) has completed. **No manual token code is required** for standard flows.
Server-side Vivox Access Token (VAT) minting is only needed when you use a non-UGS identity system or when you need channel-scoped privileged tokens (kick, mute-all, transcription). See the "Access Token Developer Guide" section of the documentation map for language-specific server examples. Do not embed HMAC signing keys in the client.
## Step 7. Validation
After writing code that uses this package:
1. Verify the project compiles without errors and that `using Unity.Services.Vivox;` resolves.
2. Confirm init order: `UnityServices.InitializeAsync` → `AuthenticationService.Instance.SignInAnonymouslyAsync` → `VivoxService.Instance.InitializeAsync` → `VivoxService.Instance.LoginAsync`.
3. No v4 legacy patterns: no `Client.Instance`, no `AccountId`, no `ChannelId`, no `ILoginSession`, no `IChannelSession`. All access goes through `VivoxService.Instance`.
4. The code subscribes to each event it consumes **before** the async call that triggers it, and unsubscribes in `OnDestroy`.
5. Channel join code does not `await` the join call as if it completes join — it subscribes to `ChannelJoined` and reacts there.
6. Directed message send uses `SendDirectTextMessageAsync` (NOT `SendDirectedTextMessageAsync`). Directed message receive uses `DirectedMessageReceived`.
7. Android builds request `RECORD_AUDIO` at runtime before joining an audio channel; iOS builds have `NSMicrophoneUsageDescription` in the plist.
8. Client code embeds no HMAC signing keys or Vivox `SECRET`/`APP_ID` — VAT-based flows are documented but delegated to a server.
## Final step
Do the following checks:
1. Check the project has zero console errors. Use `console_status` for counts.
2. Stop there unless the user asked you to prove it works or you suspect a specific fault.
3. If you do enter Play mode, do it once only to chase a fault you already suspect. Read the world through `script eval` rather than adding logging. Take no screenshots as they take too much time.
If a check fails, go back and reread the [docs pages](#full-topic-map) to find out what you missed.
## Final report
Give the user a concise but not dense checklist of what you did and why, including any incidental side effects (for example, settings you toggled to test something, or temporary files you created). If the user needs to follow up with more steps or decisions, list them. For example:
```
I made the following changes:
[✓] Created a `VivoxBootstrap.cs` script that signs in, logs in to Vivox, and joins a `team-blue` group channel.
Follow these steps to see the effect:
1. Enable Vivox for your project in the Unity Dashboard, and link the Unity project to it.
2. Add the script to a GameObject in the first scene.
3. Enter Play mode and check the Console shows no Vivox errors.
```