facebook twitter hatena line email

Unity/UniRx/値変更検知

提供: 初心者エンジニアの簡易メモ
2022年3月24日 (木) 20:50時点におけるAdmin (トーク | 投稿記録)による版

移動: 案内検索

Unity/UniRx/値変更検知/方法 Unity/UniRx/値変更検知/ObserveEveryValueChanged

ReactivePropertyを使った全体サンプル

using UnityEngine;
using UniRx;
public class ReactivePropertyScene : MonoBehaviour
{
    class SampleClient
    {
        public ReactiveProperty<bool> IsCompleted = new ReactiveProperty<bool>(false);
        public void Request()
        {
            IsCompleted.Value = true;
        }
    }
    void Start()
    {
        var sampleClient = new SampleClient();
        sampleClient.IsCompleted
            .Subscribe(value =>
            {
                if (!value) return;
                Debug.Log("Change IsCompleted : " + value);
            })
            .AddTo(gameObject);
        // 5秒後に遅延実行
        Observable.Timer(System.TimeSpan.FromSeconds(5))
            .Subscribe(_ => {
                sampleClient.Request();
            }).AddTo(gameObject);
    }
}

ObserveEveryValueChangedを使った配列内のデータを検知

毎フレームごとに処理されるので危険かも。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniRx;

public class ChangeValueListScene : MonoBehaviour
{
    class SampleClient
    {
        public List<string> Urls = new List<string>();
        public List<bool> IsCompleteds = new List<bool>();
        public SampleClient()
        {
            Urls.Add("ttp://example.com");
            Urls.Add("ttp://example2.com");
            IsCompleteds.Add(false);
            IsCompleteds.Add(false);
        }
        public void Request(int id)
        {
            IsCompleteds[id] = true;
        }
    }
    void Start()
    {
        int id = 0;
        var sampleClient = new SampleClient();
        // 毎フレームごとに処理されるので危険かも。
        var observable = Observable.EveryUpdate()
            .Subscribe(_ =>
            {
                Debug.Log("IsCompleteds.Count=" + sampleClient.IsCompleteds.Count);
                int cnt = sampleClient.IsCompleteds.Count;
                for (int tmpId = 0; tmpId < cnt; tmpId++)
                {
                    if (!sampleClient.IsCompleteds[tmpId]) continue;
                    Debug.Log("Id=" + tmpId + " sampleClient.Url=" + sampleClient.Urls[tmpId]);
                    sampleClient.IsCompleteds[tmpId] = false; // そのままにすると、連続してここが処理されるので、初期化
                }
            })
            .AddTo(gameObject);
        // 5秒後に遅延実行
        Observable.Timer(System.TimeSpan.FromSeconds(5))
            .Subscribe(_ => {
                sampleClient.Request(id);
            }).AddTo(gameObject);
    }
}