LoginSignup
36

More than 5 years have passed since last update.

[Unity] 文字列をメソッド拡張して Debug.Log をカラフルにしよう

Last updated at Posted at 2014-12-21

タイトルはちょっとふざけてますが, 地味に実用性あるかなと
思ったりするエントリーです.

前回, 『[Unity] Debug.Log で出力する文字の色を変えよう』というエントリーを
書かせてもらいました.

んで, 引き続き調べてみると色以外にもサイズ変えたりボールドにしたり
できるみたいですねこれ!! めっちゃ便利♪
http://docs.unity3d.com/Manual/StyledText.html

ただ, 色とかサイズとかスタイルとか同時に指定してたら
文字列がタグだらけになってしまいます.

そこで今回は, そうならないように文字列クラス(string)をメソッド拡張しちゃって
スマートにデコれるようにしてみました.って話です.

※実際に使いたい方は, gist に書いたのでこちらから StringExtensions.cs を
ダウンロードしてプロジェクトに追加して使ってください.

1.png

string をメソッド拡張してタグ付けを楽にする

オレオレコードを書きたい自分としてはすごく嬉しい C# のメソッド拡張使います.
んで下記のように string を拡張します.

using System;

namespace tm.Extensions {

    public static class StringExtensions {

        public static string Coloring(this string str, string color) {
            return string.Format ("<color={0}>{1}</color>", color, str);
        }
        public static string Red(this string str) {
            return str.Coloring ("red");
        }
        public static string Green(this string str) {
            return str.Coloring ("green");
        }
        public static string Blue(this string str) {
            return str.Coloring ("blue");
        }

        public static string Resize(this string str, int size) {
            return string.Format ("<size={0}>{1}</size>", size, str);
        }
        public static string Medium(this string str) {
            return str.Resize (11);
        }
        public static string Small(this string str) {
            return str.Resize (9);
        }
        public static string Large(this string str) {
            return str.Resize (16);
        }

        public static string Bold(this string str) {
            return string.Format ("<b>{0}</b>", str);
        }
        public static string Italic(this string str) {
            return string.Format ("<i>{0}</i>", str);
        }
    }

}

使い方

using tm.Extensions; すると上記のメソッド拡張が有効になるので
あとはこんな感じで書けばデコった文字が Unity の Console パネルに表示されます.

// color
Debug.Log ("Hello, world(Red)".Red ());
Debug.Log ("Hello, world(Green)".Green ());
Debug.Log ("Hello, world(Blue)".Blue ());
// size
Debug.Log ("Hello, world(Medium)".Medium());
Debug.Log ("Hello, world(Small)".Small());
Debug.Log ("Hello, world(Large)".Large());
// style
Debug.Log ("Hello, world(Bold)".Bold());
Debug.Log ("Hello, world(Italic)".Italic());

1.png

OnGUI でも♪

もちろん前回同様, OnGUI の GUI.Label とかでも使えます!

void OnGUI() {
GUI.Label (new Rect(10, 10, 100, 100), "Hello, world".Red().Large().Italic());
}

2.png

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
36