LoginSignup
0
0

More than 3 years have passed since last update.

Debugオペレータで変数を監視するのは危険(1敗)

Last updated at Posted at 2021-02-07

上の記事にある通り、Debugオペレータはとても便利なやつです
ですが、調子に乗って変数を見に行こうとするとハマるかもしれません

フォーマット文字列でDebugオペレータに変数をあげてはいけません(戒め)

問題のコード

文字列補完でDebugにTime.timeを読ませている
void Start()
{
    this.UpdateAsObservable()
        .Debug($"Time.time is: {Time.time}")
        .Subscribe(x => Debug.Log($"Time.time is: {Time.time}"));
}

実行結果

debugoptime.gif
Subscribe()内では正常に取れているのに、Debug()内ではTime.time = 0のまま!!!

つまり、Start()時点でのTime.timeを参照してしまっているわけです(^q^)

それでもしたい

力が欲しいか?
void Start()
{
    this.UpdateAsObservable()
        .Select(_ => Time.time)
        .Debug("Time.time is: ")
        .Subscribe(x => Debug.Log($"Time.time is: {Time.time}"));
}

やってやれないことはありません
observable経由で値を渡せるようにすればよいので、Select()で無理やり作ってやります

実行結果

debugoptime_select.gif
OnNext()のかっこ内に正しくTime.timeが出力されています

結論

力技なんでやめといたほうがいいと思います

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