JavaScriptRunner.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using System.Diagnostics;
  2. using System.IO;
  3. using UnityEngine;
  4. public class JavaScriptRunner : MonoBehaviour
  5. {
  6. void Start()
  7. {// 在 Android 平台上执行安装脚本
  8. #if UNITY_ANDROID && !UNITY_EDITOR
  9. string nodePath = Path.Combine(Application.streamingAssetsPath, "node-v14.21.3-linux-x64/bin/node");
  10. string installScript = $"echo \"export PATH=\\\"$PATH:{nodePath}\\\"\" >> ~/.bashrc";
  11. string[] arguments = { "-c", installScript };
  12. Process.Start(new ProcessStartInfo("/system/bin/sh", string.Join(" ", arguments)));
  13. #endif
  14. // 启动 Node.js 进程
  15. ProcessStartInfo startInfo = new ProcessStartInfo();
  16. startInfo.FileName = "node"; // Node.js 可执行文件的名称或路径
  17. startInfo.Arguments = Application.streamingAssetsPath+ "/js/build/index.js"; // 要运行的脚本文件的名称或路径
  18. startInfo.UseShellExecute = false;
  19. startInfo.RedirectStandardOutput = true;
  20. startInfo.RedirectStandardError = true;
  21. startInfo.CreateNoWindow = true;
  22. Process process = new Process();
  23. process.StartInfo = startInfo;
  24. process.OutputDataReceived += OnOutputDataReceived;
  25. process.ErrorDataReceived += OnErrorDataReceived;
  26. process.Start();
  27. process.BeginOutputReadLine();
  28. process.BeginErrorReadLine();
  29. }
  30. void OnOutputDataReceived(object sender, DataReceivedEventArgs e)
  31. {
  32. // 处理标准输出
  33. UnityEngine.Debug.Log(e.Data);
  34. }
  35. void OnErrorDataReceived(object sender, DataReceivedEventArgs e)
  36. {
  37. // 处理错误输出
  38. UnityEngine.Debug.LogError(e.Data);
  39. }
  40. }