列挙型(enum)

列挙型
列挙型
列挙型 = 特定の選択肢(カテゴリ)を定義できるデータ型のこと。
■列挙型の宣言
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | using UnityEngine; /// <summary> /// 列挙型の宣言 /// </summary> public enum TargetFruit {     None,     Apple,     Banana, } public class Fruit : MonoBehaviour {     /// <summary>     /// 選択したフルーツを格納する変数     /// </summary>     [SerializeField]     private TargetFruit _targetFruit = TargetFruit.None; } | 
【enum】これが列挙型。
【TargetFruit】という名前の新しいデータの種類。
【{None,Apple,Banana}】列挙型の値、選択肢。
private TargetFruit _targetFruit = TargetFruit.None;
これはターゲットの種類を保存する変数。
【_targetFruit】という変数を作成し型は先に記述した【TargetFruit】
デフォルトの値が【.None】
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | using UnityEngine; /// <summary> /// 列挙型の宣言 /// </summary> public enum TargetFruit {     None,     Apple,     Banana, } public class Fruit : MonoBehaviour {     /// <summary>     /// 選択したフルーツを格納する変数     /// </summary>     [SerializeField]     private TargetFruit _targetFruit = TargetFruit.None;     /// <summary>     /// 状態に応じてTag名を取得するプロパティ     /// </summary>     private string _targetTagName => _targetFruit switch     {         TargetFruit.Apple => AppleTagName,  // TargetFruit が Apple のとき "Apple" を返す         TargetFruit.Banana => BananaTagName, // TargetFruit が Banana のとき "Banana" を返す         _ => string.Empty // それ以外(None の場合)は空文字を返す     };     /// <summary>     /// Tag名の定義     /// </summary>     private const string AppleTagName = "Apple";  // リンゴのタグ名     private const string BananaTagName = "Banana"; // バナナのタグ名     private void Start()     {         /// <summary>         /// 選択されているタグ名を表示         /// </summary>         Debug.Log(_targetTagName);     } } | 
private string _targetTagName => _targetFruit switch
選択肢に応じてTag名を取得するプロパティ
【string _targetTagName】プロパティ名と型。
_targetTagNameという名前で、型をStringにする。(今欲しいのはTag名だから)
【=>】返り値 return と同じ。
【_targetFruit switch】_targetFruitの選択肢に応じてタグ名をswitchで変える。
【_ =>】Swithの最後にあるやつ。名前なしの列挙型だった場合(Apple,Bananaどちらも選択されていない場合)処理されなくなるため何か書いておく。
private const string AppleTagName = "Apple";      // リンゴのタグ名
【const】(コンスト、定数)「変更できない値」
【AppleTagName】変数名
【"Apple"】変数
switchで「AppleTagName」が呼ばれると「"Apple"」が呼ばれる。
Debug.Log(_targetTagName);
呼ばれた変数を表示させる。
処理の手順
①インスペクターの列挙型でAppleを選択する。
②実行
③列挙型が変数へ格納される。 TargetFruit.Apple
④プロパティで列挙型の選択肢に応じてTag名を定義した変数を選択。AppleTagName
⑤Tag名を定義した変数から値を取得し、プロパティが取得する。Apple
⑥Start関数からプロパティ名が表示される。Apple



