0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

UNITY標準のDebug.Log()は使い辛い

0
Posted at

UNITY標準のDebug.Log()は使い辛い

はじめに

ゲーム制作の基本は何といってもデバッグ作業である!
誰もがDebug.Log()という関数を使ったことがあるだろう。
しかしこの関数には不便な点がある。返り値がvoidである点だ。
これでは変数に代入をしながらデバッグ作業を行いたい時などは記述の量が増えて大変不便である。

NGコード例

void FixedUpdate ()
{	
if (Debug.Log(transform.grounddistances(targetLayer)>10)
{
	_isGrounded=false;
}
}

もちろんデバッグ結果出力のみを行う関数であるため返り値がなく比較対象がないため
if文の所でエラーが発生する

これをごり押しで解消しようとするとこうなる。

void FixedUpdate ()
{	
var debug=transform.grounddistances(targetLayer);
Debug.Log(debug);
if (debug>10)
{
	_isGrounded=false;
}
}

これはこれで悪くはないかもしれないが頻繁にデバッグ作業を行いたいときにはやはり非効率さを感じざるを得ない。

もっと簡単に書けないか試行錯誤した末次の拡張メソッドを記述すればうまくいくことに気が付いたので紹介をしたいと思う

解決策(拡張メソッド)

コンパイラにデバッグを走らせる処理と、値を返す処理、両方を入れた拡張メソッドを作成する。

public static T debug<T>(this T t){

Debug.Log(t);
return t;
}

この拡張メソッドを使うことで先ほどのコードと同等の処理を簡略化したコードで行うことができるようになる。

ちなみに拡張メソッドの記述法については以下の記事に記載されているのでわからない人は

実際の実用例

if (transform.grounddistances(targetLayer).debug() >10)
{
	_isGrounded=false;
}

おわりに

なぜ標準の機能でこの関数に返り値が設定されていないのかが疑問である。

0
0
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?