Skip to content

Instantly share code, notes, and snippets.

@inoook
Last active April 26, 2023 12:02
Show Gist options
  • Save inoook/185e9d416452c4f511572ec0bb07f0b2 to your computer and use it in GitHub Desktop.
Save inoook/185e9d416452c4f511572ec0bb07f0b2 to your computer and use it in GitHub Desktop.
CommandLineArgsUtils
using System;
using System.Linq;
using System.Reflection;
using UnityEngine;
public static class CommandLineArgsUtils
{
// https://github.com/baba-s/Kogane.CommandLineParser/tree/master/Editor
/**
[System.Serializable]
public class ArgData
{
public int mode = 0;
public int aaa = 0;
public bool active = false;
public override string ToString()
{
return $"mode: {mode}, aaa: {aaa}, active: {active}";
}
}
[SerializeField] ArgData argData = default;
void Start()
{
var args = CommandLineArgsUtils.ParseCommandLineArgs<ArgData>();
if (args != null)
{
argData = args;
}
}
**/
public static T ParseCommandLineArgs<T>()
{
if (!Application.isEditor)
{
string[] args = Environment.GetCommandLineArgs();
// args[0] はexeのPathが入る
if (args.Length > 1)
{
return Parse<T>(args);
}
}
return default(T);
}
public static T Parse<T>(string[] args)
{
var targetType = typeof(T);
// 指定されたクラスのインスタンスを作成する
var target = Activator.CreateInstance<T>();
// 指定されたクラスのすべてのプロパティの情報を取得する
var propertyInfoList = targetType.GetFields(BindingFlags.Instance | BindingFlags.Public);
for (int i = 0; i < args.Length; i++)
{
var argument = args[i];
// ハイフンで始まっていない引数は無視する
if (!argument.StartsWith("-")) continue;
// ハイフンを外した名前をオプション名として扱う
var optionName = argument.Remove(0, 1);
// 指定されたオプションが設定されているプロパティを検索する
var data = propertyInfoList.FirstOrDefault(x => x.Name == optionName);
// 該当するプロパティが存在しない場合は次の引数に進む
if (data == null) continue;
// フィールド値の設定
if (data.FieldType == typeof(bool))
{
// オプションがある時はtrue にする
data.SetValue(target, true);
}
else
{
// 各値をParseし設定
var value = args[i + 1];
var v = PropertyParse(data.FieldType, value);
data.SetValue(target, v);
}
}
return target;
}
/// <summary>
/// 指定された文字列を PropertyType 型に紐づくデータ型に変換して返します
/// </summary>
static object PropertyParse(Type type, string s)
{
if (type == typeof(byte))
{
return byte.Parse(s);
}
else if (type == typeof(short))
{
return short.Parse(s);
}
else if (type == typeof(int))
{
return int.Parse(s);
}
else if (type == typeof(long))
{
return long.Parse(s);
}
else if (type == typeof(ushort))
{
return ushort.Parse(s);
}
else if (type == typeof(float))
{
return float.Parse(s);
}
else if (type == typeof(double))
{
return double.Parse(s);
}
else if (type == typeof(string))
{
return s;
}
else if (type.IsEnum)
{
int v = 0;
if(int.TryParse(s, out v))
{
return v;
}
else
{
string[] texts = Enum.GetNames(type);
int index = Array.IndexOf(texts, s);
if (index > -1)
{
v = index;
}
return v;
}
}
else
{
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment