主文
構造体は値型だから値が変わらないと変化にならないよ気をつけようね
構造体
public struct TestStruct {
public int amount;
public bool flag;
}
例1
以下のコードは1秒毎にStruct has been changed
が出力される(厳密には1/200の確率で)
構造体の値が変わるから当然
ReactiveProperty<TestStruct> teststruct = new ReactiveProperty<TestStruct>(new TestStruct());
void Start () {
teststruct.Subscribe(_=>{
Debug.Log("Struct has been changed.");
});
Observable.Interval(System.TimeSpan.FromSeconds(1f)).Subscribe(_=> {
var s = teststruct.Value;
s.amount = Random.Range(1,100);
s.flag = Random.Range(0,2) == 0;
teststruct.Value = s;
});
}
例2
これも1秒毎にStruct has been changed
が出力される(厳密には1/200の確率で)
構造体の値が変わるから当然
ReactiveProperty<TestStruct> teststruct = new ReactiveProperty<TestStruct>(new TestStruct());
void Start () {
teststruct.Subscribe(_=>{
Debug.Log("Struct has been changed.");
});
Observable.Interval(System.TimeSpan.FromSeconds(1f)).Subscribe(_=> {
teststruct.Value = new TestStruct(){
amount = Random.Range(1,100),
flag = Random.Range(0,2) == 0
};
});
}
例3
この場合は1回しか出ない(初期値の代入時のみ)
初期値が1,falseで、毎回更新のたびに1,falseのものを入れてるから変化がないとの判断
ReactiveProperty<TestStruct> teststruct = new ReactiveProperty<TestStruct>(new TestStruct(){amount = 1, flag = false});
void Start () {
teststruct.Subscribe(_=>{
Debug.Log("Struct has been changed.");
});
Observable.Interval(System.TimeSpan.FromSeconds(1f)).Subscribe(_=> {
var s = teststruct.Value;
s.amount = 1;
s.flag = false;
teststruct.Value = s;
});
}
例4
これも1回しか出ない
値が変わらないとOnNextが送られない
ReactiveProperty<TestStruct> teststruct = new ReactiveProperty<TestStruct>(new TestStruct(){amount = 1, flag = false});
void Start () {
teststruct.Subscribe(_=>{
Debug.Log("Struct has been changed.");
});
Observable.Interval(System.TimeSpan.FromSeconds(1f)).Subscribe(_=> {
teststruct.Value = new TestStruct(){amount = 1, flag = false};
});
}
値が変わらなくても必ず通知して欲しい
ReactiveProperty.SetValueAndForceNotify
を使えば良い
ReactiveProperty<TestStruct> teststruct = new ReactiveProperty<TestStruct>(new TestStruct(){amount = 1, flag = false});
void Start () {
teststruct.Subscribe(_=>{
Debug.Log("Struct has been changed.");
});
Observable.Interval(System.TimeSpan.FromSeconds(1f)).Subscribe(_=> {
teststruct.SetValueAndForceNotify(new TestStruct(){amount = 1, flag = false} );
});
}