I am very new in codding, especially with ChatGPT, so here is my C# code in unity for a InputText:
using System.Collections;
using System;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class TextHandler : MonoBehaviour
{
public InputField inputField;
public Text outputText;
[System.Serializable]
public class GptResponse
{
public Choice[ ] choices;
}
[System.Serializable]
public class Choice
{
public string text;
}
public void HandleInput()
{
string userInput = inputField.text;
StartCoroutine(SendToGPT(userInput));
}
private IEnumerator SendToGPT(string input)
{
string apiUrl = "url";
string requestBody = "{\"prompt\": \"" + input + "\", \"max_tokens\": 500}";
UnityWebRequest request = UnityWebRequest.PostWwwForm(apiUrl, requestBody);
request.SetRequestHeader("Content-Type", "application/json");
request.SetRequestHeader("Authorization", "Bearer myapi");
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.Success)
{
string responseJson = request.downloadHandler.text;
string generatedText = ParseResponseFromJSON(responseJson);
yield return generatedText;
}
else
{
Debug.LogError("Error sending request: " + request.error);
yield return null;
}
}
private string ParseResponseFromJSON(string jsonResponse)
{
try
{
GptResponse response = JsonUtility.FromJson<GptResponse>(jsonResponse);
if (response.choices != null && response.choices.Length > 0)
{
string generatedText = response.choices[0].text;
return generatedText;
}
else
{
Debug.LogError("No choices found in JSON response.");
return "Error: No choices found in JSON response.";
}
}
catch (Exception e)
{
Debug.LogError("Error parsing JSON response: " + e.Message);
return "Error parsing JSON response";
}
}
}
After writing the text in the inputbox it waits for like 2 seconds and gives me this error:
Error sending request: HTTP/1.1 400 Bad Request
UnityEngine.Debug:LogError (object)
TextHandler/d__5:MoveNext () (at Assets/Scripts/TextHandler.cs:67)
UnityEngine.SetupCoroutine:InvokeMoveNext (System.Collections.IEnumerator,intptr)