1
2

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.

(メモ)uGUIButtonにおけるOnClick()追加の自動化とEnumによる管理

Posted at

Buttonはよく使う割にコードの追加が面倒
1.Editor上でOnClick()追加するのが面倒
2.クラスが増えがち
3.String管理は嫌い

継承とEnumで管理する。

ButtonController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ButtonController : MonoBehaviour
{
    public ButtonController button;
    [SerializeField]
    ChildButtonController.ButttonName butName;
# if UNITY_EDITOR
    Button but;
    void Reset()
    {
        but = GetComponent<Button>();
        UnityEditor.Events.UnityEventTools.RemovePersistentListener<GameObject>(but.onClick, OnClick);
        UnityEditor.Events.UnityEventTools.AddObjectPersistentListener<GameObject>(but.onClick, OnClick, gameObject);
    }
# endif
    void Start()
    {
        //改善の余地あり
        button = GameObject.Find("Canvas").transform.Find("ChildButtonController").GetComponent<ChildButtonController>();
    }
    public void OnClick(GameObject obj)
    {
        button.Click(butName);
    }
    protected virtual void Click(ChildButtonController.ButttonName buttonName)
    {
    }
}
ChildButtonController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class ChildButtonController : ButtonController
{
    [SerializeField]
    Object Turret;
    protected override void Click(ButttonName buttonName)
    {
        switch (buttonName)
        {
            case ButttonName.Test: TestMethod(); break;
        }
    }
    void TestMethod()
    {
        Debug.Log("TEST");
    }
    public enum ButttonName
    {
        Test
    }
}

使い方はButtonController.csをButtonのオブジェクトにアタッチして目的の機能のEnumを選び、Canvas直下にChildButtonControllerクラスを持つChildButtonControllerを作成しておく。
以上により自分でOnClick()追加せずに、2つのクラスでEnumで管理することができる。

参考文献
UnityのuGUIでButtonクリック時のスクリプト呼び出しを共通化しよう!
エディター操作で登録するのが面倒なボタンのクリックイベントを、スクリプトで登録する - テラシュールブログ

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?