Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Last active October 15, 2026 18:50
Show Gist options
  • Select an option

  • Save unitycoder/bab1c3945d44d0e49e1c35e9a0f42d84 to your computer and use it in GitHub Desktop.

Select an option

Save unitycoder/bab1c3945d44d0e49e1c35e9a0f42d84 to your computer and use it in GitHub Desktop.
1 Click Solution to Copy Scripts from ChatGPT Code Blocks into Unity Editor + GreaseMonkey UserScript
// Editor tool to receive code snippets from ChatGPT and save them as C# scripts in the Unity project.
// You need to install GreaseMonkey or Tampermonkey in your browser and use the following userscript
// Note: Enable Run in Background in Unity Editor: Player Settings > Resolution and Presentation > Run In Background
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;
#if UNITY_EDITOR_WIN
using System.Runtime.InteropServices;
#endif
namespace UnityLibrary.EditorTools
{
[InitializeOnLoad]
internal static class ChatGPTCodeReceiver
{
private const int Port = 8765;
private const int MaxMessageBytes = 2 * 1024 * 1024;
private const string ServerEnabledKey = "ChatGPTCodeReceiver.ServerEnabled";
private const string FocusAfterSaveKey = "ChatGPTCodeReceiver.FocusAfterSave";
private static HttpListener listener;
private static CancellationTokenSource cancellation;
private static bool isRunning;
private static readonly ConcurrentQueue<string> pendingImports = new ConcurrentQueue<string>();
private static readonly object fileWriteLock = new object();
static ChatGPTCodeReceiver()
{
EditorApplication.delayCall += () =>
{
if (EditorPrefs.GetBool(ServerEnabledKey, false)) Start();
};
EditorApplication.quitting += Stop;
AssemblyReloadEvents.beforeAssemblyReload += Stop;
}
internal static bool IsRunning => isRunning;
internal static string Endpoint => "http://127.0.0.1:" + Port + "/send";
internal static bool FocusAfterSave
{
get => EditorPrefs.GetBool(FocusAfterSaveKey, true);
set => EditorPrefs.SetBool(FocusAfterSaveKey, value);
}
internal static void Start()
{
if (isRunning) return;
try
{
cancellation = new CancellationTokenSource();
listener = new HttpListener();
listener.Prefixes.Add("http://127.0.0.1:" + Port + "/");
listener.Start();
isRunning = true;
EditorApplication.update += ProcessPendingImports;
_ = AcceptConnections(cancellation.Token);
Debug.Log("ChatGPT code receiver listening on http://127.0.0.1:" + Port + "/send");
}
catch (Exception exception)
{
Stop();
Debug.LogError("Could not start ChatGPT code receiver: " + exception.Message +
". Check whether port " + Port + " is already in use.");
}
}
internal static void StartFromWindow()
{
EditorPrefs.SetBool(ServerEnabledKey, true);
Start();
}
internal static void StopFromWindow()
{
EditorPrefs.SetBool(ServerEnabledKey, false);
Stop();
}
private static void Stop()
{
isRunning = false;
EditorApplication.update -= ProcessPendingImports;
cancellation?.Cancel();
try { listener?.Stop(); } catch { }
listener?.Close();
listener = null;
cancellation?.Dispose();
cancellation = null;
}
private static async Task AcceptConnections(CancellationToken token)
{
while (!token.IsCancellationRequested && listener != null && listener.IsListening)
{
HttpListenerContext context;
try { context = await listener.GetContextAsync(); }
catch (HttpListenerException) { break; }
catch (ObjectDisposedException) { break; }
if (context.Request.HttpMethod == "OPTIONS")
{
context.Response.StatusCode = 204;
AddCorsHeaders(context.Response);
context.Response.Close();
continue;
}
if (context.Request.HttpMethod == "POST" && context.Request.Url.AbsolutePath == "/send")
{
_ = HandleHttpRequest(context, token);
continue;
}
if (!context.Request.IsWebSocketRequest)
{
context.Response.StatusCode = 404;
context.Response.Close();
continue;
}
_ = HandleClient(context, token);
}
}
private static async Task HandleHttpRequest(HttpListenerContext context, CancellationToken token)
{
try
{
if (context.Request.ContentLength64 > MaxMessageBytes)
throw new InvalidDataException("Request exceeds the 2 MB limit.");
string json;
using (var reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding))
json = await reader.ReadToEndAsync();
if (Encoding.UTF8.GetByteCount(json) > MaxMessageBytes)
throw new InvalidDataException("Request exceeds the 2 MB limit.");
var request = JsonUtility.FromJson<WriteRequest>(json);
var response = SaveToDisk(request);
var bytes = Encoding.UTF8.GetBytes(JsonUtility.ToJson(response));
AddCorsHeaders(context.Response);
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.StatusCode = response.ok ? 200 : 400;
context.Response.OutputStream.Write(bytes, 0, bytes.Length);
}
catch (Exception exception)
{
AddCorsHeaders(context.Response);
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.StatusCode = 400;
var bytes = Encoding.UTF8.GetBytes(JsonUtility.ToJson(
new WriteResponse { ok = false, error = exception.Message }));
try { context.Response.OutputStream.Write(bytes, 0, bytes.Length); } catch { }
}
finally { context.Response.Close(); }
}
private static void AddCorsHeaders(HttpListenerResponse response)
{
response.Headers["Access-Control-Allow-Origin"] = "https://chatgpt.com";
response.Headers["Access-Control-Allow-Methods"] = "POST, OPTIONS";
response.Headers["Access-Control-Allow-Headers"] = "Content-Type";
}
private static async Task HandleClient(HttpListenerContext context, CancellationToken token)
{
WebSocket socket = null;
try
{
socket = (await context.AcceptWebSocketAsync(null)).WebSocket;
var buffer = new byte[8192];
using (var stream = new MemoryStream())
{
WebSocketReceiveResult result;
do
{
result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), token);
if (result.MessageType == WebSocketMessageType.Close) return;
if (result.MessageType != WebSocketMessageType.Text)
throw new InvalidDataException("Only text messages are accepted.");
if (stream.Length + result.Count > MaxMessageBytes)
throw new InvalidDataException("Request exceeds the 2 MB limit.");
stream.Write(buffer, 0, result.Count);
} while (!result.EndOfMessage);
var json = Encoding.UTF8.GetString(stream.ToArray());
var request = JsonUtility.FromJson<WriteRequest>(json);
var response = SaveToDisk(request);
var bytes = Encoding.UTF8.GetBytes(JsonUtility.ToJson(response));
await socket.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, true, token);
}
}
catch (Exception exception)
{
if (socket != null && socket.State == WebSocketState.Open)
{
var bytes = Encoding.UTF8.GetBytes(JsonUtility.ToJson(
new WriteResponse { ok = false, error = exception.Message }));
try { await socket.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, true, token); }
catch { }
}
}
finally
{
if (socket != null) socket.Dispose();
}
}
private static WriteResponse SaveToDisk(WriteRequest request)
{
try
{
if (request == null || request.type != "write-script")
throw new InvalidDataException("Unsupported request.");
if (string.IsNullOrWhiteSpace(request.code))
throw new InvalidDataException("Code is empty.");
if (request.destination != "scripts" && request.destination != "editor")
throw new InvalidDataException("Destination must be scripts or editor.");
var folder = request.destination == "editor" ? "Assets/Editor" : "Assets/Scripts";
var name = Path.GetFileNameWithoutExtension(request.fileName);
if (string.IsNullOrWhiteSpace(name)) name = InferClassName(request.code);
name = SanitizeFileName(name);
if (string.IsNullOrEmpty(name)) name = "ChatGPTScript";
var path = folder + "/" + name + ".cs";
lock (fileWriteLock)
{
Directory.CreateDirectory(folder);
if (File.Exists(path)) MoveToRecycleBin(path);
File.WriteAllText(path, request.code, new UTF8Encoding(false));
}
pendingImports.Enqueue(path);
return new WriteResponse { ok = true, path = path };
}
catch (Exception exception)
{
return new WriteResponse { ok = false, error = exception.Message };
}
}
private static void ProcessPendingImports()
{
while (pendingImports.TryDequeue(out var path))
{
try
{
if (FocusAfterSave) FocusUnityEditor();
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
Debug.Log("Received ChatGPT code at " + path);
}
catch (Exception exception) { Debug.LogError("Could not import " + path + ": " + exception.Message); }
}
}
private static void MoveToRecycleBin(string path)
{
#if UNITY_EDITOR_WIN
var operation = new ShellFileOperation
{
operation = 3,
from = Path.GetFullPath(path) + "\0\0",
flags = 0x0040 | 0x0010 | 0x0004 | 0x0400
};
var result = SHFileOperation(ref operation);
if (result != 0 || operation.aborted)
throw new IOException("Could not move the existing script to the Recycle Bin.");
#else
if (!FileUtil.MoveFileOrDirectoryToTrash(path))
throw new IOException("Could not move the existing script to the system trash.");
#endif
}
#if UNITY_EDITOR_WIN
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct ShellFileOperation
{
public IntPtr owner;
public uint operation;
[MarshalAs(UnmanagedType.LPWStr)] public string from;
[MarshalAs(UnmanagedType.LPWStr)] public string to;
public ushort flags;
[MarshalAs(UnmanagedType.Bool)] public bool aborted;
public IntPtr mappings;
[MarshalAs(UnmanagedType.LPWStr)] public string progressTitle;
}
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
private static extern int SHFileOperation(ref ShellFileOperation operation);
[StructLayout(LayoutKind.Sequential)]
private struct FlashWindowInfo
{
public uint size;
public IntPtr windowHandle;
public uint flags;
public uint count;
public uint timeout;
}
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetForegroundWindow(IntPtr windowHandle);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool ShowWindowAsync(IntPtr windowHandle, int command);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FlashWindowEx(ref FlashWindowInfo info);
#endif
private static void FocusUnityEditor()
{
#if UNITY_EDITOR_WIN
var windowHandle = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
if (windowHandle != IntPtr.Zero)
{
const int RestoreWindow = 9;
const uint FlashTray = 0x00000002;
const uint FlashTimerNoForeground = 0x0000000C;
ShowWindowAsync(windowHandle, RestoreWindow);
SetForegroundWindow(windowHandle);
if (GetForegroundWindow() != windowHandle)
{
var info = new FlashWindowInfo
{
size = (uint)Marshal.SizeOf(typeof(FlashWindowInfo)),
windowHandle = windowHandle,
flags = FlashTray | FlashTimerNoForeground,
count = 3,
timeout = 0
};
FlashWindowEx(ref info);
}
}
#endif
EditorUtility.FocusProjectWindow();
}
private static string InferClassName(string code)
{
var match = System.Text.RegularExpressions.Regex.Match(
code, @"\b(?:class|struct|interface|enum)\s+([A-Za-z_][A-Za-z0-9_]*)");
return match.Success ? match.Groups[1].Value : "ChatGPTScript";
}
private static string SanitizeFileName(string value)
{
foreach (var invalid in Path.GetInvalidFileNameChars()) value = value.Replace(invalid, '_');
value = System.Text.RegularExpressions.Regex.Replace(value, @"[^A-Za-z0-9_.-]", "_");
return value.Trim('.', ' ');
}
[Serializable]
private sealed class WriteRequest
{
public string type;
public string destination;
public string code;
public string fileName;
public string language;
}
[Serializable]
private sealed class WriteResponse
{
public string type = "write-result";
public bool ok;
public string path;
public string error;
}
}
internal sealed class ChatGPTCodeReceiverWindow : EditorWindow
{
[MenuItem("Tools/UnityLibrary/ChatGPT Code Receiver/Open Window")]
private static void Open()
{
var window = GetWindow<ChatGPTCodeReceiverWindow>("ChatGPT to Unity");
window.minSize = new Vector2(320, 150);
window.Show();
}
private void OnGUI()
{
EditorGUILayout.LabelField("ChatGPT Code Receiver", EditorStyles.boldLabel);
EditorGUILayout.Space(4);
EditorGUILayout.LabelField("Endpoint", ChatGPTCodeReceiver.Endpoint);
EditorGUILayout.LabelField("Status", ChatGPTCodeReceiver.IsRunning ? "Running" : "Stopped");
EditorGUILayout.Space(8);
using (new EditorGUILayout.HorizontalScope())
{
GUI.enabled = !ChatGPTCodeReceiver.IsRunning;
if (GUILayout.Button("Start Server", GUILayout.Height(28)))
ChatGPTCodeReceiver.StartFromWindow();
GUI.enabled = ChatGPTCodeReceiver.IsRunning;
if (GUILayout.Button("Stop Server", GUILayout.Height(28)))
ChatGPTCodeReceiver.StopFromWindow();
GUI.enabled = true;
}
EditorGUILayout.Space(6);
ChatGPTCodeReceiver.FocusAfterSave = EditorGUILayout.ToggleLeft(
"Focus Unity after receiving and compiling a script", ChatGPTCodeReceiver.FocusAfterSave);
if (GUI.changed) Repaint();
}
}
}
// ==UserScript==
// @name ChatGPT Code to Unity
// @namespace kelobyte.chatgpt-unity
// @version 1.1.0
// @description Send ChatGPT code blocks to the active Unity Editor project.
// @match https://chatgpt.com/*
// @match https://chat.openai.com/*
// @grant GM_xmlhttpRequest
// @grant GM.xmlHttpRequest
// @connect 127.0.0.1
// @connect localhost
// ==/UserScript==
(function () {
"use strict";
const HTTP_URL = "http://127.0.0.1:8765/send";
const BUTTON_CLASS = "cg2u-send-button";
function addStyle() {
if (document.getElementById("cg2u-style")) return;
const style = document.createElement("style");
style.id = "cg2u-style";
style.textContent = "." + BUTTON_CLASS + "{appearance:none;border:1px solid #555;border-radius:7px;background:#2f3035;color:#f2f2f2;padding:5px 9px;margin-left:6px;font:500 12px/1.2 system-ui,sans-serif;cursor:pointer;white-space:nowrap}." + BUTTON_CLASS + ":hover{background:#41434a}." + BUTTON_CLASS + ":disabled{opacity:.55;cursor:wait}";
document.head.appendChild(style);
}
function showStatus(button, message, isError) {
button.textContent = message;
button.style.color = isError ? "#ff9a9a" : "#9ee6a8";
setTimeout(() => {
if (!button.isConnected) return;
button.textContent = button.dataset.label;
button.style.color = "";
button.disabled = false;
}, 2200);
}
function sendToUnity(code, destination, button) {
if (!code.trim()) return showStatus(button, "Empty code", true);
button.disabled = true;
button.textContent = "Connecting...";
const payload = JSON.stringify({ type: "write-script", destination, code, fileName: "", language: "" });
const request = typeof GM_xmlhttpRequest === "function"
? GM_xmlhttpRequest
: typeof GM !== "undefined" && typeof GM.xmlHttpRequest === "function"
? GM.xmlHttpRequest.bind(GM)
: null;
if (!request) {
console.error("ChatGPT Code to Unity: GM_xmlhttpRequest and GM.xmlHttpRequest are unavailable. Check the userscript grants and reload ChatGPT.");
return showStatus(button, "Enable GM request", true);
}
request({
method: "POST",
url: HTTP_URL,
headers: { "Content-Type": "application/json" },
data: payload,
timeout: 8000,
onload: response => {
try {
const result = JSON.parse(response.responseText);
if (response.status === 200 && result.ok)
showStatus(button, "Sent: " + result.path, false);
else showStatus(button, result.error || "Send failed", true);
} catch { showStatus(button, "Invalid response", true); }
},
onerror: error => {
console.error("ChatGPT Code to Unity request failed:", error);
showStatus(button, "Unity unavailable", true);
},
ontimeout: () => showStatus(button, "Unity timed out", true),
onabort: () => showStatus(button, "Request cancelled", true)
});
}
function addButton(container, code, destination, label) {
if ([...container.querySelectorAll("." + BUTTON_CLASS)]
.some(button => button.dataset.destination === destination)) return;
const button = document.createElement("button");
button.type = "button";
button.className = BUTTON_CLASS;
button.textContent = label;
button.dataset.label = label;
button.dataset.destination = destination;
button.title = destination === "editor" ? "Save under Assets/Editor" : "Save under Assets/Scripts";
button.addEventListener("click", () => sendToUnity(code, destination, button));
container.appendChild(button);
}
function processCodeBlocks() {
addStyle();
document.querySelectorAll('[data-code-block="true"]').forEach(block => {
const actionBar = block.querySelector('[data-markdown-copy="exclude"]');
const codeElement = block.querySelector("pre code, pre");
if (!actionBar || !codeElement) return;
const code = codeElement.innerText || codeElement.textContent || "";
addButton(actionBar, code, "scripts", "Send to Unity");
addButton(actionBar, code, "editor", "Send as Editor Script");
});
}
new MutationObserver(processCodeBlocks).observe(document.documentElement, { childList: true, subtree: true });
processCodeBlocks();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment