代码展示:
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
的数组,其中包含一个包含role
和content
字段的对象。
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
类包含一个名为message
的Message
对象。Message
类包含一个名为content
的字段,用于存储翻译后的文本。
这些类使用了Unity的[Serializable]
特性,这意味着Unity编辑器可以显示和编辑这些类的属性。
总结 :
脚本的主要功能是使用Unity的UnityWebRequest
与智谱清言的API进行交互,以实现文本翻译功能。当用户在游戏运行时输入文本时,它会发送一个POST请求到API进行翻译,并将翻译结果显示在Unity UI中的translatedTextDisplay
组件上。