前提・実現したいこと
Unityでリバーシゲームを作っているのですが、その際に標準入出力を用いて、石の打つ場所を入力、現在の盤面の出力、をしたいと思っています。
石の置く場所を入力 例) 3 4 -> 処理 GameManager.cs --- ゲーム進行 Board.cs --- 盤面の管理 DataDisplay.cs --- 石の数などをゲーム画面上に表示 -> 出力 現在の盤面(8x8)を出力 (0:なし 1:黒石 2:白石) 例) 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 0 0 0 0 0 0 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
発生している問題
調べたところ、C#のProcessクラスとUnityのStreamingAssetsの機能を使っていけばいい、ように思うのですが、今の課題「コンソール画面(Unityのものではなく)を表示させて、それに任意の文字列を入力、出力させる」の解決にはなりませんでした。
試したこと
とりあえず、UnityのPlayモード中にxキーとzキーを押すと、それぞれ文字列がUnityのデバッグコンソール上に出力されるものはできました。
<追記> (参考) https://www.hanachiru-blog.com/entry/2021/12/13/120000
ただ、コンソール画面(Unityのものではなく)を表示させて、それに任意の文字列を入力、出力させるようなことはできませんでした。
・与えられた入力をそのまま返すexeのプログラム
<追記> このexe(StdInputApp.exe)の場所は、Assets/StreamingAssets/StdInputApp/StdInputApp.exe
です。
cs
using System; namespace StdInputApp { public class Program { private const string ExitLine = "exit"; private static void Main(string[] args) { while (true) { var line = Console.ReadLine(); if (line is null or ExitLine) break; Console.WriteLine(line); } } } }
・上のexeを読み込み、Unity側で起動させるプログラム
cs
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using UnityEngine; public class ConsoleClient : MonoBehaviour { private static readonly string FolderPath = Application.streamingAssetsPath + "/StdInputApp"; private static readonly string FilePath = FolderPath + "/StdInputApp.exe"; private Process _process; private void Start() { _process = new Process(); _process.StartInfo = new ProcessStartInfo { FileName = FilePath, UseShellExecute = false, WorkingDirectory = FolderPath, RedirectStandardInput = true, RedirectStandardOutput = true, CreateNoWindow = true, }; _process.OutputDataReceived += OnStandardOut; _process.EnableRaisingEvents = true; _process.Exited += DisposeProcess; _process.Start(); _process.BeginOutputReadLine(); } void Update() { if (Input.GetKeyDown(KeyCode.Z)) { _process?.StandardInput.WriteLine("Hello, World!"); } if (Input.GetKeyDown(KeyCode.X)) { _process?.StandardInput.WriteLine("Onaka suita."); } } private static void OnStandardOut(object sender, DataReceivedEventArgs e) => UnityEngine.Debug.Log($"外部プロセスの標準出力 : {e.Data}"); private void DisposeProcess(object sender, EventArgs e) => DisposeProcess(); private void DisposeProcess() { if (_process == null || _process.HasExited) return; _process.StandardInput.Close(); _process.CloseMainWindow(); _process.Dispose(); _process = null; } }
使用バージョンなど
Unity 2021.2.16f1
まだ回答がついていません
会員登録して回答してみよう