2
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?

More than 3 years have passed since last update.

UnityのButtonクラスのOnClickのFunctionの引数にEnumを設定する方法

Posted at

UnityのButtonクラスのOnClickのFunctionの引数にEnumを設定する方法についてのメモです。
通常、UnityのButtonクラスのOnClickのFunctionの引数には、boolやint、stringなどは使えますが、enumを使用する事はできません。
これが不便だったので解決方法を考えました。

他にも方法はあると思うのですが、ひとまずシンプルな方法で解決したので備忘録としてメモしておきます。

Unityエディターの右クリックメニューから「UI」→「Button」を選択し、ボタンを作り、そのオブジェクトに下にあるEnumOnClickクラスのスクリプトをAddComponentし、ヒエラルキー上からstateを選択して設定をします。
ButtonクラスのOnClickの個所は「List is Empty」の状態のままで大丈夫です。

起動後にButtonのOnClickを確認しても「List is Empty」のままになっており、AddListenerに失敗しているように見えますが、クリックすると正常に動きます。
検証していませんが、起動時の情報しか反映されないのかもしれません。

EnumOnClick.cs
using UnityEngine;
using UnityEngine.UI;

public class EnumOnClick : MonoBehaviour
{
    //この値をインスペクター上から設定します
    [SerializeField] private State state;
    private Button button;

    public enum State
    {
        NONE,
        GAME_START,
        OPTION,
        EXIT,
    }

    private void Awake()
    {
        button = GetComponent<Button>();
        button.onClick.AddListener(OnClickButton);
    }

    public void OnClickButton()
    {
        if (state != State.NONE)
        {
            //stateに応じた処理
            switch (state)
            {
                case State.GAME_START:
                    break;

                case State.OPTION:
                    break;

                case State.EXIT:
                    break;
            }
        }
    }
}
2
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
2
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?