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?

More than 3 years have passed since last update.

OnValidate関数を使ってUnityEventの登録をスクリプトから行いたい

Last updated at Posted at 2020-03-13

備忘録

OnValidate関数知らない人用

Unityで元々用意されている関数です。
UnityEditorで手動でやっていること(コンポーネントのアタッチとか)を自動化できます。
今回はイベントの登録をスクリプト側からやってもらいます。

公式の説明
https://docs.unity3d.com/jp/460/ScriptReference/MonoBehaviour.OnValidate.html

コード

TestCode.cs
using UnityEngine;

public class TestCode : MonoBehaviour
{
    public UnityEngine.Events.UnityEvent hogehogeEvent;

    private void OnValidate()
    {
# if UNITY_EDITOR
        // 既にボタンにイベントを登録していたら削除する.
        UnityEditor.Events.UnityEventTools.RemovePersistentListener(hogehogeEvent, TestCallback);
        // ボタンにイベントを登録する.
        UnityEditor.Events.UnityEventTools.AddPersistentListener(hogehogeEvent, TestCallback);
# endif
    }

    private void Start()
    {
        // イベントの呼び出し
        hogehogeEvent.Invoke();
    }

    private void TestCallback()
    {
        Debug.Log("イベントが呼ばれました");
    }
}

結果

image.png

ボタンの場合

sample.cs

using System;
using UnityEngine;
using UnityEngine.UI;

    [RequireComponent(typeof(Button))]
    public class TestCode: MonoBehaviour
    {
        [SerializeField]
        private Button button;

        private void OnValidate()
        {
# if UNITY_EDITOR
            if (button)
            {
                return;
            }

            button = GetComponent<Button>();
            UnityEditor.Events.UnityEventTools.RemovePersistentListener(button.onClick, OnPressedButton);
            UnityEditor.Events.UnityEventTools.AddPersistentListener(button.onClick, OnPressedButton);
# endif
        }

        private void OnPressedButton()
        {
          
        }
    }
}

呼び出し先のメソッドをprivateにできるのも好きです

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?