Skip to content

Instantly share code, notes, and snippets.

@mao-test-h
Last active March 29, 2019 07:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mao-test-h/145f54c8251a46fb34ec608cb4826bd7 to your computer and use it in GitHub Desktop.
Save mao-test-h/145f54c8251a46fb34ec608cb4826bd7 to your computer and use it in GitHub Desktop.
[SerializeField] private 変数にdefault代入してくれる君
// Unity2018.3からprivateな[SerializeField]が初期化しないと警告吐くようになってきたので、
// 各CSソースを解析して一括で"= default;"を付ける奴。
// ※ sedコマンドとかでも出来なくは無いが..改行や既存の代入などを踏まえるとこっちの方が早かった。
namespace Tools // HACK: 適当なので都合に合わせて命名
{
using System;
using System.IO;
using UnityEngine;
using UnityEditor;
public static class InsertDefault
{
// 解析対象のフォルダ
const string FindFolder = "/_Samples";
// ------------------------------------------------------
#region // Impl
const string SerializeFieldLiteral = "[SerializeField]";
const string DefaultLiteral = " = default";
[MenuItem("Insert Default/Execute")]
public static void Execute()
{
Debug.Log("Execute Insert Default");
var dirInfo = new DirectoryInfo($"{Application.dataPath}/{FindFolder}");
var files = dirInfo.GetFiles("*.cs", SearchOption.AllDirectories);
foreach (var file in files)
{
var path = file.ToString();
Debug.Log(path);
var lines = File.ReadAllLines(path);
var writeLines = new string[lines.Length];
var isChange = false;
for (var i = 0; i < lines.Length; i++)
{
var currentLine = lines[i];
try
{
if (currentLine.Trim() == SerializeFieldLiteral && (i + 1 < lines.Length))
{
// 空白を抜いた上で[SerializeField]と完全一致していたら改行された位置にあるとみなす
// TODO: 例えば以下の様な書き方をされたらアカンけど現状未対応。何か発生したら頑張る。
// - 属性定義後に改行を挟んだ後に変数宣言
// - 属性定義後にコメント行
writeLines[i] = currentLine;
writeLines[i + 1] = AddDefault(lines[i + 1], ref isChange);
++i;
}
else if (currentLine.IndexOf(SerializeFieldLiteral, StringComparison.Ordinal) != -1)
{
// 同じ行にある想定
writeLines[i] = AddDefault(currentLine, ref isChange);
}
else
{
writeLines[i] = currentLine;
}
}
catch (Exception e)
{
// TODOに書いてある内容とかでダメだったら握りつぶして次のファイルを対応
Debug.LogException(e);
Debug.LogError($"ErrorFile : {path}, {currentLine}");
writeLines = null;
break;
}
}
if (writeLines == null || !isChange) continue;
Debug.Log($" >>>>> Changed : {path}");
File.WriteAllLines(path, writeLines);
}
AssetDatabase.Refresh();
Debug.Log("Complete!");
}
static string AddDefault(string str, ref bool isChanged)
{
// 挿入対象の文字列に"="が入っていたら代入済みとみなして無視
if (str.IndexOf("=", StringComparison.Ordinal) != -1)
{
return str;
}
isChanged = true;
var semicolonIndex = str.IndexOf(";", StringComparison.Ordinal);
return str.Insert(semicolonIndex, DefaultLiteral);
}
#endregion // Impl
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment