前提・実現したいこと
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
1using System; 2 3namespace StdInputApp 4{ 5 public class Program 6 { 7 private const string ExitLine = "exit"; 8 9 private static void Main(string[] args) 10 { 11 while (true) 12 { 13 var line = Console.ReadLine(); 14 15 if (line is null or ExitLine) break; 16 17 Console.WriteLine(line); 18 } 19 } 20 } 21}
・上のexeを読み込み、Unity側で起動させるプログラム
cs
1using System; 2using System.Collections; 3using System.Collections.Generic; 4using System.Diagnostics; 5using UnityEngine; 6 7public class ConsoleClient : MonoBehaviour 8{ 9 private static readonly string FolderPath = Application.streamingAssetsPath + "/StdInputApp"; 10 private static readonly string FilePath = FolderPath + "/StdInputApp.exe"; 11 12 private Process _process; 13 14 private void Start() 15 { 16 _process = new Process(); 17 _process.StartInfo = new ProcessStartInfo 18 { 19 FileName = FilePath, 20 UseShellExecute = false, 21 WorkingDirectory = FolderPath, 22 RedirectStandardInput = true, 23 RedirectStandardOutput = true, 24 CreateNoWindow = true, 25 }; 26 27 _process.OutputDataReceived += OnStandardOut; 28 29 _process.EnableRaisingEvents = true; 30 _process.Exited += DisposeProcess; 31 32 _process.Start(); 33 _process.BeginOutputReadLine(); 34 } 35 36 void Update() 37 { 38 if (Input.GetKeyDown(KeyCode.Z)) 39 { 40 _process?.StandardInput.WriteLine("Hello, World!"); 41 } 42 43 if (Input.GetKeyDown(KeyCode.X)) 44 { 45 _process?.StandardInput.WriteLine("Onaka suita."); 46 } 47 } 48 49 private static void OnStandardOut(object sender, DataReceivedEventArgs e) 50 => UnityEngine.Debug.Log($"外部プロセスの標準出力 : {e.Data}"); 51 52 private void DisposeProcess(object sender, EventArgs e) 53 => DisposeProcess(); 54 55 private void DisposeProcess() 56 { 57 if (_process == null || _process.HasExited) return; 58 59 _process.StandardInput.Close(); 60 _process.CloseMainWindow(); 61 _process.Dispose(); 62 _process = null; 63 } 64} 65
使用バージョンなど
Unity 2021.2.16f1
回答1件
あなたの回答
tips
プレビュー