Unity调用智谱API(简单操作 文本实时翻译)

代码展示: 
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class ZhiPuAi : MonoBehaviour
{
    // API的端点URL
    public string apiEndpoint = "https://open.bigmodel.cn/api/paas/v4/chat/completions";
    // API密钥,用于身份验证
    public string apiKey = "API_Key"; // 替换为您的API密钥

    public Text textToTranslate;
    public Text translatedTextDisplay;
    //翻译为的语种
    public string YuYan = "英语";

    // 游戏启动时自动调用翻译功能
    void Start()
    {
        string textToTranslateContent = textToTranslate.text;
        StartCoroutine(CallTranslateAPI(textToTranslateContent));
    }


    // 协程方法,用于发送翻译API请求
    IEnumerator CallTranslateAPI(string text)
    {
        string jsonData = BuildJsonData(text);
        using (UnityWebRequest request = new UnityWebRequest(apiEndpoint, "POST"))
        {
            byte[] postData = System.Text.Encoding.UTF8.GetBytes(jsonData);
            request.uploadHandler = (UploadHandler)new UploadHandlerRaw(postData);
            request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
            request.SetRequestHeader("Authorization", "Bearer " + apiKey);
            request.SetRequestHeader("Content-Type", "application/json");

            yield return request.SendWebRequest();

            if (request.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError($"Error: {request.error}");
            }
            else
            {
                Debug.Log($"Successfully accessed API endpoint. Response: {request.downloadHandler.text}");
                // 处理响应数据
                Response response = JsonConvert.DeserializeObject<Response>(request.downloadHandler.text);
                if (response.choices != null && response.choices.Length > 0)
                {
                    Choice choice = response.choices[0];
                    Debug.Log($"Translation found: {choice.message.content}");
                    translatedTextDisplay.text = choice.message.content;
                }
                else
                {
                    Debug.LogError("No translations found in the response.");
                }
            }
        }
    }

    // 根据API的要求构建JSON数据
    string BuildJsonData(string text)
    {
        // 这里需要根据智谱清言API的要求构建JSON数据
        // 假设API要求如下格式:{"model": "glm-4", "messages": [{"role": "user", "content": "你好"}]}

        return "{\"model\": \"glm-4\",\"messages\": [{\"role\": \"user\",\"content\": \""+"请把," + text +",翻译为"+ YuYan+"\"}]}";
    }

    // 定义用于解析JSON响应的序列化类
    [System.Serializable]
    public class Response
    {
        public Choice[] choices;
    }

    // 定义翻译结果的序列化类
    [System.Serializable]
    public class Choice
    {
        public Message message;
    }

    // 定义消息的序列化类
    [System.Serializable]
    public class Message
    {
        public string content;

    }
}

让我们逐步分析每个部分:

1. 导入必要的命名空间

using Newtonsoft.Json; // 导入用于序列化和反序列化JSON数据的库
using System; // 导入System命名空间,包含常用的基础类型和类
using System.Collections; // 导入System.Collections命名空间,包含IEnumerator接口
using System.Collections.Generic; // 导入System.Collections.Generic命名空间,包含泛型集合类
using UnityEngine; // 导入Unity引擎的基本功能
using UnityEngine.Networking; // 导入Unity的网络请求相关功能
using UnityEngine.UI; // 导入Unity UI相关功能

这些导入语句允许我们使用脚本中定义的类和方法。

2. 定义公开的Unity组件引用

public Text textToTranslate; // Unity场景中的Text组件,用于显示要翻译的文本
public Text translatedTextDisplay; // Unity场景中的Text组件,用于显示翻译后的文本
// 翻译为的语种
public string YuYan = "英语";

这些变量引用Unity场景中的Text组件,用于显示要翻译的文本和翻译后的文本。

3. 游戏启动时自动调用翻译功能

void Start()
{
    string textToTranslateContent = textToTranslate.text;
    StartCoroutine(CallTranslateAPI(textToTranslateContent));
}

在游戏启动时,脚本会自动调用CallTranslateAPI协程,以便在游戏启动时翻译文本。

4. 协程方法,用于发送翻译API请求

IEnumerator CallTranslateAPI(string text)
{
    string jsonData = BuildJsonData(text);
    using (UnityWebRequest request = new UnityWebRequest(apiEndpoint, "POST"))
    {
        byte[] postData = System.Text.Encoding.UTF8.GetBytes(jsonData);
        request.uploadHandler = (UploadHandler)new UploadHandlerRaw(postData);
        request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
        request.SetRequestHeader("Authorization", "Bearer " + apiKey);
        request.SetRequestHeader("Content-Type", "application/json");

        yield return request.SendWebRequest();

        if (request.result != UnityWebRequest.Result.Success)
        {
            Debug.LogError($"Error: {request.error}");
        }
        else
        {
            Debug.Log($"Successfully accessed API endpoint. Response: {request.downloadHandler.text}");
            // 处理响应数据
            Response response = JsonConvert.DeserializeObject<Response>(request.downloadHandler.text);
            if (response.choices != null && response.choices.Length > 0)
            {
                Choice choice = response.choices[0];
                Debug.Log($"Translation found: {choice.message.content}");
                translatedTextDisplay.text = choice.message.content;
            }
            else
            {
                Debug.LogError("No translations found in the response.");
            }
        }
    }
}

CallTranslateAPI方法是一个协程,它负责构建JSON格式的请求数据,创建一个UnityWebRequest对象,发送POST请求到API,并处理响应。如果响应成功,它将解析JSON数据,提取翻译结果,并将其显示在Unity UI中的translatedTextDisplay组件上。

5. 根据API的要求构建JSON数据

string BuildJsonData(string text)
{
    // 这里需要根据智谱清言API的要求构建JSON数据
    // 假设API要求如下格式:{"model": "glm-4", "messages": [{"role": "user", "content": "你好"}]}

    return "{\"model\": \"glm-4\",\"messages\": [{\"role\": \"user\",\"content\": \""+"请把," + text +",翻译为"+ YuYan+"\"}]}";
}

BuildJsonData方法根据API的要求构建JSON格式的请求数据。在这个例子中,它假设API要求包含一个名为model的字段和一个名为messages的数组,其中包含一个包含rolecontent字段的对象。

6. 定义用于解析JSON响应的序列化类

[System.Serializable]
public class Response
{
    public Choice[] choices;
}

[System.Serializable]
public class Choice
{
    public Message message;
}

[System.Serializable]
public class Message
{
    public string content;
}

这三个类定义了API响应数据的结构。Response类包含一个名为choices的数组,其中包含Choice对象的数组。Choice类包含一个名为messageMessage对象。Message类包含一个名为content的字段,用于存储翻译后的文本。

这些类使用了Unity的[Serializable]特性,这意味着Unity编辑器可以显示和编辑这些类的属性。 

总结 :

脚本的主要功能是使用Unity的UnityWebRequest与智谱清言的API进行交互,以实现文本翻译功能。当用户在游戏运行时输入文本时,它会发送一个POST请求到API进行翻译,并将翻译结果显示在Unity UI中的translatedTextDisplay组件上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南無忘码至尊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值