
- 作者: 吉谷幹人,布留川英一,一條貴彰,西森丈俊,藤岡裕吾,室星亮太,車谷勇人,湊新平,土屋つかさ,黒河優介,中村優一,牙竜,コポコポ,かせ,hataken,monmoko,佐藤英一
- 出版社/メーカー: ボーンデジタル
- 発売日: 2018/05/01
- メディア: 大型本
- この商品を含むブログを見る
序文
『UNITYゲーム プログラミング・バイブル』11日目?
Unityの勉強会があんまり盛況じゃない(気がする)のは、職業プログラマ的には「なんか違う」感があるんだろうか。とか考えた。
Rails使ってます!ってのとあんまり変わらない気がするけど。
進捗
(学習時間:2時間)
コード実装部分
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; // 属性を自作する // AttributeUsage(AttributeTargets.Method)で // メソッドにのみ適用できる属性であることを示している [AttributeUsage(AttributeTargets.Method)] class SampleAttribute : Attribute { } // 引数ありの属性の作り方1 class Sample2Attribute : Attribute { internal readonly string Name; internal Sample2Attribute(string name) { this.Name = name; } } // 引数ありの属性の作り方2 class Sample3Attribute : Attribute { public string Name { get; set; } } namespace _180724AttributeSample { class Program { static void Main(string[] args) { // #ifを使ったデバッグビルドでだけ実行させる書き方(面倒くさい) #if DEBUG ifDebugDump(); #endif // 属性を使用したデバッグビルドでだけ実行させる attrDebugDump(); // 属性を使用して非推奨メソッドであることを示す oldMethod(); // プログラムからpublicなメソッドをとりだして foreach(var n in typeof(Program).GetMethods()) { // [SampleAttribute]属性をもつメソッドだけを実行する // [SampleAttribute]は[Sample]と書いても良い // GetCustomAttributes()メソッドの第二引数がtrueだと継承元を検索しに行くらしい if (n.GetCustomAttributes(typeof(SampleAttribute), false).Length > 0) { n.Invoke(null, null); } // [Sample2Attribute]属性を取り出して foreach (var m in n.GetCustomAttributes(typeof(Sample2Attribute), false)) { // 属性の引数を表示する Console.WriteLine(((Sample2Attribute)m).Name); } // [Sample2Attribute]属性を取り出して foreach (var m in n.GetCustomAttributes(typeof(Sample3Attribute), false)) { // 属性の引数を表示する Console.WriteLine(((Sample3Attribute)m).Name); } } } // #ifを使ったデバッグビルドでだけ実行させる書き方(面倒くさい) #if DEBUG private static void ifDebugDump() { Console.WriteLine("This is a if debug version."); } #endif // 属性を使用してデバッグビルドでだけ実行させる [Conditional("DEBUG")] private static void attrDebugDump() { Console.WriteLine("This is a attribute debug version."); } // 属性を使用して非推奨メソッドであることを示す [Obsolete] private static void oldMethod() { Console.WriteLine("This is a old version."); } // 独自の属性も使える [Sample] public static void sampleMethod() { Console.WriteLine("This is a sample."); } // 引数ありの属性 [Sample2("Taro")] public static void sample2Method() { Console.WriteLine("This is a sample2."); } // 引数ありの属性 [Sample3(Name = "Hanako")] public static void sample3Method() { Console.WriteLine("This is a sample3."); } } }
実行結果
感想
TextMesh Proの概要を学習して、さぁいよいよノベルゲームの実装だ!と思ったのもつかの間、サンプルコード見て壁に激突。
作っていきますとか言って、ほとんど説明してくれてないしさぁ。
とりあえずソースコード読んでいくかと思って、[System.Serializable]をコメントアウトした瞬間、シナリオデータが消去されて心が折れた。笑
そういえば、あんまり属性とかわかってないなぁと思って、今日はC#の属性のふるまいについて勉強していました。
実際ほとんど使ったことないなぁ…。それこそ[System.Serializable]だけちょこっと使った記憶があるけど…。
一応、書き方とか[Obsolete]属性とかは理解できたけど、自作属性をどういう場合に使えば効果的なのかとかはよくわかってない。
カロリーメイトください。
BGM
ある光 / 小沢健二
www.youtube.com
これヤバいよね