> For the complete documentation index, see [llms.txt](https://docs.convai.com/api-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/unity-plugin/utilities/managing-sessionid-locally.md). Agents can also search and read this documentation through its [MCP server](https://docs.convai.com/api-docs/~gitbook/mcp).

# 本地管理 sessionID

会话 ID 管理——为 Convai Unity 集成管理唯一的会话 ID。

在典型的集成 Convai API 的应用程序中，在不同会话之间保持一致的会话 ID，对于提供流畅的用户体验至关重要。本文档概述了使用 Unity 的 `PlayerPrefs`存储和检索会话 ID 的最佳实践，其中包含详细步骤和示例脚本。

## **会话 ID 的重要性**

会话 ID 用于唯一标识客户端与 Convai 服务器之间的会话。在本地存储会话 ID，可确保不同会话中使用相同的会话 ID，从而有助于在交互过程中保持上下文和连贯性。

## **存储会话 ID**

初始化会话时，如果本地没有会话 ID，应从服务器获取，然后存储在本地以供将来使用。具体操作如下：

1. **获取并存储会话 ID**：初始化会话时，检查本地是否存储了会话 ID。如果没有，则从服务器获取新的会话 ID，并使用 `PlayerPrefs`.

```csharp
public static async Task<string> InitializeSessionIDAsync(string characterName, ConvaiService.ConvaiServiceClient client, string characterID)
{
    // Retrieve stored session ID if it exists
    string sessionID = PlayerPrefs.GetString(characterID, string.Empty);

    // If no session ID is stored, initialize a new one
    if (string.IsNullOrEmpty(sessionID))
    {
        sessionID = await ConvaiGRPCAPI.InitializeSessionIDAsync(characterName, client, characterID, sessionID);

        // Store the new session ID locally
        if (!string.IsNullOrEmpty(sessionID))
        {
            PlayerPrefs.SetString(characterID, sessionID);
            PlayerPrefs.Save();
        }
    }

    return sessionID;
}
```

## **检索会话 ID**

初始化应用程序时，检索已存储的会话 ID，以确保用户交互的连贯性。

```csharp
private async void Start()
{
    // Initialize session ID on start
    string characterID = "YourCharacterID"; // Replace with your actual character ID
    string sessionID = await InitializeSessionIDAsync("CharacterName", grpcClient, characterID);

    if (!string.IsNullOrEmpty(sessionID))
    {
        Debug.Log("Session ID initialized and stored: " + sessionID);
    }
    else
    {
        Debug.LogError("Failed to initialize session ID.");
    }
}
```

## 会话管理示例类

以下示例类演示如何在 Unity 项目中使用 `PlayerPrefs` 管理会话 ID：

```csharp
using System;
using System.Threading.Tasks;
using Convai.Scripts.Utils;
using Google.Protobuf;
using Grpc.Core;
using Service;
using UnityEngine;
using static Service.GetResponseRequest.Types;

public class SessionManager : MonoBehaviour
{
    public ConvaiService.ConvaiServiceClient grpcClient;

    private void Start()
    {
        // Initialize session ID on start
        InitializeSession("CharacterName", grpcClient, "YourCharacterID");
    }

    private async void InitializeSession(string characterName, ConvaiService.ConvaiServiceClient client, string characterID)
    {
        string sessionID = await InitializeSessionIDAsync(characterName, client, characterID);

        if (!string.IsNullOrEmpty(sessionID))
        {
            Debug.Log("Session ID initialized and stored: " + sessionID);
        }
        else
        {
            Debug.LogError("Failed to initialize session ID.");
        }
    }

    public static async Task<string> InitializeSessionIDAsync(string characterName, ConvaiService.ConvaiServiceClient client, string characterID)
    {
        string sessionID = PlayerPrefs.GetString(characterID, string.Empty);

        if (string.IsNullOrEmpty(sessionID))
        {
            sessionID = await ConvaiGRPCAPI.InitializeSessionIDAsync(characterName, client, characterID, sessionID);

            if (!string.IsNullOrEmpty(sessionID))
            {
                PlayerPrefs.SetString(characterID, sessionID);
                PlayerPrefs.Save();
            }
        }

        return sessionID;
    }
}
```

## 会话管理详细步骤

1. **初始化会话**：调用 `InitializeSessionIDAsync` 以检查是否已存储会话 ID。如果没有，则获取并存储。
2. **存储会话 ID**：使用 `PlayerPrefs.SetString(characterID, sessionID)` 在本地存储会话 ID。
3. **获取会话 ID**：使用 `PlayerPrefs.GetString(characterID, string.Empty)` 获取已存储的会话 ID。
4. **使用会话 ID**：在调用 Convai API 时传入会话 ID，以保持会话连续性。

## 最佳实践

* **错误处理**：获取和存储会话 ID 时，请确保进行适当的错误处理。
* **安全性**：考虑对存储在 `PlayerPrefs`.
* **性能**：使用异步方法，避免获取会话 ID 时阻塞主线程。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/unity-plugin/utilities/managing-sessionid-locally.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
