forked from microsoft/AirSim
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_unity_script.cs
More file actions
92 lines (77 loc) · 2.9 KB
/
example_unity_script.cs
File metadata and controls
92 lines (77 loc) · 2.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
public class SelfDrivingCar : MonoBehaviour
{
private const string OpenAIEndpoint = "https://api.openai.com/v1/engines/davinci-codex/completions";
[SerializeField] private string apiKey = "<YOUR_API_KEY>";
private Coroutine currentRequestCoroutine;
private void Start()
{
// Start the self-driving behavior
StartSelfDriving();
}
private void StartSelfDriving()
{
// Continuously request actions from OpenAI
currentRequestCoroutine = StartCoroutine(RequestOpenAIAction());
}
private void StopSelfDriving()
{
// Stop requesting actions from OpenAI
if (currentRequestCoroutine != null)
StopCoroutine(currentRequestCoroutine);
}
private IEnumerator RequestOpenAIAction()
{
while (true)
{
// Prepare the request data
string prompt = "The car is currently at position (x, y) = (" + transform.position.x + ", " + transform.position.y + ").";
string requestData = "{ \"prompt\": \"" + prompt + "\", \"max_tokens\": 1 }";
// Create and send the HTTP request to OpenAI
UnityWebRequest request = UnityWebRequest.Post(OpenAIEndpoint, requestData);
request.SetRequestHeader("Authorization", "Bearer " + apiKey);
request.SetRequestHeader("Content-Type", "application/json");
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.Success)
{
// Process the response from OpenAI
string responseJson = request.downloadHandler.text;
OpenAIResponse response = JsonUtility.FromJson<OpenAIResponse>(responseJson);
if (response != null && response.choices != null && response.choices.Length > 0)
{
string action = response.choices[0].text.Trim();
Debug.Log("Action received from OpenAI: " + action);
// Perform the action (e.g., steer the car)
// Implement your own logic here based on the received action
}
else
{
Debug.LogWarning("Invalid or empty response from OpenAI.");
}
}
else
{
Debug.LogWarning("Error requesting action from OpenAI: " + request.error);
}
// Delay before sending the next request
yield return new WaitForSeconds(1f);
}
}
private void OnDestroy()
{
// Stop self-driving when the object is destroyed
StopSelfDriving();
}
[System.Serializable]
private class OpenAIResponse
{
public OpenAIChoice[] choices;
}
[System.Serializable]
private class OpenAIChoice
{
public string text;
}
}