You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Unity脚本运行并访问JavaScript后端应用

Unity与JavaScript后端交互实现方案

一、启动JavaScript后端

你之前尝试的ScriptManager方案不适用于.NET 8.0环境,Unity中可以通过System.Diagnostics.Process直接启动Node.js进程(假设你的JS后端基于Node.js开发),具体实现如下:

  1. 先确认Unity项目已配置为.NET 8.0:打开Player Settings,将Scripting Runtime Version设置为.NET 8.x。
  2. 编写启动后端的C#脚本:
using System.Diagnostics;
using UnityEngine;

public class BackendLauncher : MonoBehaviour
{
    // 填写你的JS后端入口文件路径,例如"Assets/Backend/server.js"
    public string backendScriptPath;
    // Node.exe路径,已加入系统环境变量则直接填"node"
    public string nodeExecPath = "node";

    public void StartBackendService()
    {
        ProcessStartInfo startConfig = new ProcessStartInfo
        {
            FileName = nodeExecPath,
            Arguments = backendScriptPath,
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            CreateNoWindow = true
        };

        Process backendProcess = new Process();
        backendProcess.StartInfo = startConfig;
        backendProcess.Start();

        // 可选:监听后端输出与错误日志
        backendProcess.OutputDataReceived += (sender, e) =>
        {
            if (!string.IsNullOrEmpty(e.Data))
            {
                Debug.Log($"Backend Log: {e.Data}");
            }
        };
        backendProcess.ErrorDataReceived += (sender, e) =>
        {
            if (!string.IsNullOrEmpty(e.Data))
            {
                Debug.LogError($"Backend Error: {e.Data}");
            }
        };
        backendProcess.BeginOutputReadLine();
        backendProcess.BeginErrorReadLine();
    }
}

使用方式:将脚本挂载到场景GameObject上,在Inspector面板中设置backendScriptPath,调用StartBackendService方法即可启动后端。

二、Unity发起HTTP请求(注册/登录/用户创建)

JS后端需提供对应的API接口(如POST /register、POST /login),Unity可通过两种方式发起请求:

方式1:使用UnityWebRequest(Unity官方推荐)

using UnityEngine;
using UnityEngine.Networking;

public class UserAPIClient : MonoBehaviour
{
    // 填写后端服务地址,例如"http://localhost:3000"
    public string backendBaseUrl;

    // 用户注册
    public IEnumerator Register(string username, string password, string email)
    {
        WWWForm form = new WWWForm();
        form.AddField("username", username);
        form.AddField("password", password);
        form.AddField("email", email);

        using (UnityWebRequest request = UnityWebRequest.Post($"{backendBaseUrl}/register", form))
        {
            yield return request.SendWebRequest();

            if (request.result == UnityWebRequest.Result.Success)
            {
                Debug.Log("注册成功:" + request.downloadHandler.text);
                // 处理注册成功逻辑,如跳转登录界面
            }
            else
            {
                Debug.LogError("注册失败:" + request.error);
            }
        }
    }

    // 用户登录
    public IEnumerator Login(string username, string password)
    {
        WWWForm form = new WWWForm();
        form.AddField("username", username);
        form.AddField("password", password);

        using (UnityWebRequest request = UnityWebRequest.Post($"{backendBaseUrl}/login", form))
        {
            yield return request.SendWebRequest();

            if (request.result == UnityWebRequest.Result.Success)
            {
                Debug.Log("登录成功:" + request.downloadHandler.text);
                // 保存登录凭证,如Token
                string authToken = request.downloadHandler.text;
                PlayerPrefs.SetString("AuthToken", authToken);
            }
            else
            {
                Debug.LogError("登录失败:" + request.error);
            }
        }
    }
}

调用示例(UI按钮点击事件):

public void OnRegisterBtnClick()
{
    string username = usernameInput.text;
    string password = passwordInput.text;
    string email = emailInput.text;
    StartCoroutine(userAPIClient.Register(username, password, email));
}

方式2:使用HttpClient(.NET 8.0支持)

如果项目基于.NET 8.0,也可以用HttpClient实现异步请求:

using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using System.Text.Json;

public class UserAPIClient : MonoBehaviour
{
    public string backendBaseUrl;
    private HttpClient _httpClient;

    void Awake()
    {
        _httpClient = new HttpClient();
    }

    // 异步注册
    public async Task RegisterAsync(string username, string password, string email)
    {
        var userData = new { username = username, password = password, email = email };
        string jsonData = JsonSerializer.Serialize(userData);
        var requestContent = new StringContent(jsonData, Encoding.UTF8, "application/json");

        try
        {
            HttpResponseMessage response = await _httpClient.PostAsync($"{backendBaseUrl}/register", requestContent);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            Debug.Log("注册成功:" + responseBody);
        }
        catch (HttpRequestException e)
        {
            Debug.LogError("注册失败:" + e.Message);
        }
    }

    // 异步登录
    public async Task LoginAsync(string username, string password)
    {
        var loginData = new { username = username, password = password };
        string jsonData = JsonSerializer.Serialize(loginData);
        var requestContent = new StringContent(jsonData, Encoding.UTF8, "application/json");

        try
        {
            HttpResponseMessage response = await _httpClient.PostAsync($"{backendBaseUrl}/login", requestContent);
            response.EnsureSuccessStatusCode();
            string authToken = await response.Content.ReadAsStringAsync();
            Debug.Log("登录成功,Token:" + authToken);
            PlayerPrefs.SetString("AuthToken", authToken);
        }
        catch (HttpRequestException e)
        {
            Debug.LogError("登录失败:" + e.Message);
        }
    }
}

调用示例:

public async void OnLoginBtnClick()
{
    string username = usernameInput.text;
    string password = passwordInput.text;
    await userAPIClient.LoginAsync(username, password);
}

三、关键注意事项

  • 跨域问题:若Unity编辑器请求后端出现跨域错误,需在JS后端配置CORS(例如使用cors中间件),允许Unity的访问地址。
  • 路径正确性:启动后端时,若Node.exe未加入系统环境变量,需填写绝对路径(如C:\\Program Files\\nodejs\\node.exe)。
  • 安全性:客户端代码不要硬编码敏感信息(如数据库连接串);登录返回的Token需妥善保存,后续请求需携带Token做身份验证。

内容的提问来源于stack exchange,提问作者SikiMiki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 07:06:11