0
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

コードを生成するコードを作ると人生が楽になる 【Unity】

0
Last updated at Posted at 2019-12-18

シーン・サウンド・エフェクト等が追加された事で変数も新しく追加で用意する必要が出てきて
何回も決まりきった流れのコードを追記していく経験はありませんか

これはコードの自動生成で対策することが出来ます。

なにか難しそうに感じると思うのですが、とても単純でコード文を書いてファイル出力するだけで作れます

作り方

   private static string ASSETS_PATH = Application.dataPath + "/";
   private static string SOURCE_TEMPLATE =
    @"public class #SCRIPTNAME#
    {
    }";
    
    /// <summary>
    /// ソース出力
    /// </summary>
    /// <param name="fileName"></param>
    private static void CreateSource(string fileName)
    {
        // インポート開始
        AssetDatabase.StartAssetEditing();

        StreamWriter cs = new StreamWriter(ASSETS_PATH + fileName + ".cs", false, Encoding.UTF8);

        // 書き出すコードを組み立てる
        StringBuilder stringBuilder = new StringBuilder(SOURCE_TEMPLATE);
        
        // ※ここで用途に合わせ追記

        // ファイルにコードを書き込む
        cs.Write(stringBuilder);

        // ファイルを閉じる
        cs.Close();

        // インポート終了
        AssetDatabase.StopAssetEditing();

        // アセットインポートする
        AssetDatabase.Refresh(ImportAssetOptions.ImportRecursive);
    }

次回はこの仕組みを使って何か便利な仕組みを紹介できればと考えています。

0
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?