Unityで変数の監視を行う

2023/04/01に公開

監視をしたい

ゲームを作成していると、共通で使用している変数など監視したくなります。

ScriptableObject編

public class GameStatus : ScriptableObject
{
    private int _point;

    public int Point
    {
        get => _point;
        set
        {
            _point = value;
            OnPointChanged?.Invoke(value);
        }
    }
    
    public event System.Action<int> OnPointChanged;
}

public class GameStatusObserver : MonoBehaviour
{
    private void OnEnable()
    {
        _gameStatus.OnPointChanged += OnPointChanged;
    }

    private void OnDisable()
    {
        _gameStatus.OnPointChanged -= OnPointChanged;
    }

    private void OnPointChanged(int value)
    {
        Debug.Log("Point changed to " + value);
    }

}

GameStatusクラスは、ScriptableObjectを継承して実際のファイルを作成します。

_pointはセッター内で、OnPointChangedを設定しています。

Pointに値が挿入されたら、イベントが実行されます。

GameStatusObserverでは、OnPointChangedに関数を設置していて監視を行っています。

UniRx 編

// 監視されるクラス
public class VolEntity
{
    private ReactiveProperty<float> _bgmVolume = new(0);
    // 外部から監視するためのプロパティ
    public IObservable<float> BgmVolume => _bgmVolume;

    public void SetVolume(float volume)
    {
        _bgmVolume.Value += volume;
    }
}
// 監視するクラスの例えばStartメソッド
void Start(){
     var _volEntity = new VolEntity();
     
     // 変数が変更されたのを監視。検知したらOnBgmChangeが実行される
     _volEntity.BgmVolume.Subscribe(value => OnBgmChange(value));
}

Discussion