はじめに
今回はAddlistenerした後GameObjectを破棄するとRemoveListenerしてくれるUnityEvent拡張メソッドを作成していきます。
環境は Unity 2021.3.25f1です
UniRx7.1 を使用しています。
スクリプト
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using UniRx; using System; /// <summary> /// Event拡張クラス /// </summary> public static class EventExtension { /// <summary> /// イベントの登録と同時に削除時にRemoveListenerするように設定する /// </summary> /// <param name="evnt"></param> /// <param name="action"></param> /// <param name="obj"></param> /// <returns></returns> public static IDisposable Subscribe(this UnityEvent evnt,UnityAction action) { evnt.AddListener(action); var disposable = Disposable.Create(() => evnt.RemoveListener(action)); return disposable; } public static IDisposable Subscribe<T0>(this UnityEvent<T0> evnt, UnityAction<T0> action) { evnt.AddListener(action); var disposable = Disposable.Create(() => evnt.RemoveListener(action)); return disposable; } public static IDisposable Subscribe<T0,T1>(this UnityEvent<T0,T1> evnt, UnityAction<T0,T1> action) { evnt.AddListener(action); var disposable = Disposable.Create(() => evnt.RemoveListener(action)); return disposable; } public static IDisposable Subscribe<T0, T1,T2>(this UnityEvent<T0, T1, T2> evnt, UnityAction<T0, T1, T2> action) { evnt.AddListener(action); var disposable = Disposable.Create(() => evnt.RemoveListener(action)); return disposable; } }
使い方
Subscribeで登録してAddToに指定したものがdestroyされたときにRemoveListenerしてくれます
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UniRx; public class UITest : MonoBehaviour { [SerializeField] Button button; void Start() { button.onClick.Subscribe(() => TestLog()).AddTo(this); } public void TestLog() { Debug.Log("onClick"); } }
参考