0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

UnityでのC#文法 〜enum編

Posted at

enumの使いどき

Unityでゲームを作っていると、こんなコードを書いた経験はないでしょうか。

string state = "Attack";
int state = 1; // 0:待機 1:移動 2:攻撃

このように状態管理を数字や文字列で行うのは、少々面倒くさいです。

数字の場合意味がコードから読み取りにくいですし、文字列の場合打ち間違えてもエラーになりません。

そこで登場するのが、 enum(列挙型) です。

enumとは何か

列挙型とは、 取りうる値をあらかじめ列挙しておく型 です。

public enum PlayerState
{
    Wait,
    Move,
    Attack
}

この時点で、
・PlayerState.Wait
・PlayerState.Move
・PlayerState.Attack
この3つ以外の値は代入できません。

enumの基本文法

いくつか独自の文法があります。

enumの宣言

public enum GameState
{
    Title,
    Playing,
    GameOver
}

enunキーワードで宣言します。

enum型の変数を使う

public class GameManager : MonoBehaviour
{
    public GameState currentState;

    void Start()
    {
        currentState = GameState.Title;
    }
}

intやstringとは違い、 無関係な値を代入できない のが大きなメリットです。

Switch文と組み合わせて使う

enum型ととても相性がいいのが、Switch文です。

void Update()
{
    switch (currentState)
    {
        case GameState.Title:
            // タイトル画面の処理
            break;

        case GameState.Playing:
            // ゲーム中の処理
            break;

        case GameState.GameOver:
            // ゲームオーバー処理
            break;
    }
}

可読性が非常に高く、状態が増えても管理がしやすいのが特徴です。

enumの注意点

・状態を増やしすぎない
いくら可読性が高いと言っても、あまりに数が多いと処理が大変です。乱用は避けましょう。

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?