Skip to content

Instantly share code, notes, and snippets.

@t5ujiri
Last active December 19, 2017 07:42
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 t5ujiri/d3242c4391c85d856de2d3bcb6adc18d to your computer and use it in GitHub Desktop.
Save t5ujiri/d3242c4391c85d856de2d3bcb6adc18d to your computer and use it in GitHub Desktop.
Unity文字操作の処理
using UnityEngine;
using UnityEditor;
using System.IO;
namespace ScriptNamespace
{
public class AddCustomNameSpace : UnityEditor.AssetModificationProcessor
{
public static void OnWillCreateAsset(string path)
{
var setting = Resources.Load("NewScriptSetting") as NewScriptSetting;
if (setting == null) return;
var namespaceString = setting.nameSpace;
var filePath = path.Replace(".meta", "");
if (System.IO.Path.GetExtension(filePath) != ".cs") return;
var index = Application.dataPath.LastIndexOf("Assets", System.StringComparison.Ordinal);
var absoluteFilePath = Application.dataPath.Substring(0, index) + filePath;
using (var stream = new FileStream(absoluteFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
using (var reader = new StreamReader(stream))
{
using (var writer = new StreamWriter(stream))
{
var texts = reader.ReadToEnd();
stream.Position = 0;
var lines = texts.Split('\n');
// 全行にインデント
for (int i = 0; i < lines.Length; i++)
{
lines[i] = lines[i].Insert(0, "\t");
}
texts = string.Join("\n", lines);
texts = texts.Insert(0, string.Format("namespace {0}\n{1}\n", namespaceString, System.Text.RegularExpressions.Regex.Unescape("{")));
texts = texts.Insert(texts.Length - 1, "}\n");
writer.Write(texts);
}
}
}
AssetDatabase.Refresh();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment