Created
April 17, 2021 12:06
-
-
Save the6th/a7feedfda3790fcb61ea7803f8a8594b to your computer and use it in GitHub Desktop.
UnityでCLIアプリケーションを作成するサンプル。Mono.Optionsでコマンドの解析
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Mono.Options; | |
using System; | |
using System.Collections.Generic; | |
using System.Threading.Tasks; | |
using UnityEngine; | |
public class StdinReader : MonoBehaviour | |
{ | |
private string stringValue = ""; | |
private int number = 0; | |
private bool help = false; | |
OptionSet options; | |
void Start() | |
{ | |
#if !UNITY_SERVER | |
return;//Server Buildでは無い時は無視する | |
#endif | |
//CLIアプリケーションの場合、UIの描画はされないので、 | |
//処理内容によってはフレームレートを抑えることで | |
//CPUの負荷も減らすことができる。 | |
Application.targetFrameRate = 10; | |
options = new OptionSet() | |
{ | |
// string 型の引数を取るオプション | |
{ "v|value=", "specify a value.", v => stringValue = v }, | |
// string 型以外の引数を取るオプション | |
{ "n|number=", "specify a number.", (int v) => number = v }, | |
// 引数を取らないオプション | |
{ "h|help", "show help.", v => help = v != null }, | |
// 引数を持たないメソッドをコール | |
{ "t|test", "call test method", v => TestMethod()}, | |
// 引数を持つメソッドをコール | |
{ "x|xmethod=", "call test method2", v => TestMethod2(v) }, | |
}; | |
string[] args = System.Environment.GetCommandLineArgs(); | |
ParseCommandLineArgs(System.Environment.GetCommandLineArgs()); | |
Task.Run(() => | |
{ | |
string line; | |
Console.WriteLine("CLI task start"); | |
while (true) | |
{ | |
if ((line = Console.ReadLine()) != null) | |
{ | |
args = line.Split(' '); | |
ParseCommandLineArgs(args); | |
} | |
Task.Delay(100); | |
} | |
}); | |
} | |
void ParseCommandLineArgs(string[] args) | |
{ | |
List<string> extra; | |
try | |
{ | |
extra = options.Parse(args); | |
Console.WriteLine($"value={stringValue}"); | |
Console.WriteLine($"number={number}"); | |
if (help) options.WriteOptionDescriptions(Console.Out); | |
} | |
catch (OptionException e) | |
{ | |
Console.WriteLine(e.Message); | |
} | |
Console.WriteLine("GetLine:" + string.Join(" ", args)); | |
} | |
void TestMethod() | |
{ | |
Console.WriteLine("call TestMethod"); | |
} | |
void TestMethod2(string _v) | |
{ | |
Console.WriteLine("call TestMethod2:" + _v); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment