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

server/2024/10/21 3:57:36/
代码展示: 
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的端点URLpublic 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组件上。


http://www.ppmy.cn/server/38983.html

相关文章

银行卡OCR识别接口快速对接

银行卡OCR识别接口又叫银行卡卡面信息识别接口、银行卡文字信息识别API接口&#xff0c;指的是传入银行卡照片&#xff0c;精准识别静态银行卡图像上的文字信息&#xff0c;包括银行卡号、卡类型、银行名称等。那么银行卡OCR识别接口如何快速对接呢&#xff1f; 首先我们找到一…

力扣题目101:对称二叉树

作者介绍&#xff1a;10年大厂数据\经营分析经验&#xff0c;现任大厂数据部门负责人。 会一些的技术&#xff1a;数据分析、算法、SQL、大数据相关、python 欢迎加入社区&#xff1a;码上找工作 作者专栏每日更新&#xff1a; LeetCode解锁1000题: 打怪升级之旅 python数据分析…

var, let, const 的区别

var, let, const 是JavaScript中用于声明变量的关键字。 var&#xff1a;可以声明变量&#xff0c;没有块级作用域的概念&#xff0c;可以重复声明变量&#xff0c;其值可以改变。 var x 10; // 声明变量x var x 20; // 重新声明变量x&#xff0c;值改变 console.log(x); /…

使用PyMuPDF(fitz)提取PDF文件文本内容

安装PyMuPDF库&#xff08;如果还没有安装的话&#xff09;&#xff1a; pip install pymupdf使用以下Python脚本来提取指定页面的文本&#xff1a; import fitz # 导入PyMuPDF库def extract_text_from_specific_page(file_path, page_number):# 打开PDF文件doc fitz.open(…

unity基础(一)

内容概要&#xff1a; 生命周期函数vector3 位置 方向 缩放旋转等信息Vector3欧拉角和Quaternion四元素unity脚本执行顺序设置 一 生命周期函数 方法说明Awake最早调用,所以一般可以再此实现单例模式OnEnable组件激活后调用,在Awake后会调用一次Start在Update之前调用一次&a…

【退役之重学Java】如何保证从消息队列里拿到的消息顺序执行

一、场景 MySQL binlog 同步数据&#xff0c;比如大数据team。在MySQL中进行增删改查&#xff0c;将其 binlog 发送到 MQ 里面&#xff0c;到消费出来执行&#xff0c;这里就必须要保证其顺序执行&#xff0c;不然数据库就会错乱。 二、如何保证消息的顺序性呢&#xff1f; …

二、Redis五种常用数据类型-String

1、用途 简单的K-V缓存计数器分布式锁session共享分布式ID生成(自增) 2、底层实现结构 Redis底层是c语言实现的&#xff0c;但是并没有使用c的string来表示字符串&#xff0c;而是使用自己的简单动态字符串的抽象类型(simple dynamic string,SDS)。 SDS结构&#xff1a; st…

【思考讨论】如何利用AI提高内容生产效率?

1. 自动化内容生成 利用人工智能&#xff08;AI&#xff09;提高内容生产效率&#xff0c;尤其是在自动化内容生成方面&#xff0c;已经成为媒体、营销、教育等多个领域的热门话题。随着自然语言处理&#xff08;NLP&#xff09;、机器学习、深度学习等技术的飞速发展&#xf…