Unityを使っていく上で、知っておくと便利そうなTipsをメモしていきます。
以前Unityを始めたばかりのころに、「Unityを触り始めたのでメモ(C#編)」という記事を書いているので、よかったらそちらも見てみてください。
オブジェクトの位置を元に、スクリーンにGUIをオーバーレイさせる
Unityのドキュメントを見ていて知ったやつです。
例えばプレイヤーの位置にHPバーを表示したり、名前を表示したり、みたいなやつです。
using UnityEngine;
using System.Collections;
public class HealthBar : MonoBehaviour
{
GUIStyle healthStyle;
GUIStyle backStyle;
void OnGUI() {
InitStyles();
// Draw a health bar.
Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
// draw health bar background
GUI.color = Color.grey;
GUI.backgroundColor = Color.grey;
GUI.Box(new Rect(pos.x - 26, Screen.height - pos.y + 20, 10), ".", backStyle);
// draw health bar
GUI.color = Color.green;
GUI.backgroundColor = Color.green;
GUI.Box(new Rect(pos.x - 25, Screen.height - pos.y + 21, 5), ".", healthStyle);
}
void InitStyles() {
if (healthStyle == null) {
healthStyle = new GUIStyle(GUI.skin.box);
healthStyle.normal.background = MakeTex(2, 2, new Color(0f, 1f, 0f, 1f));
}
if (backStyle == null) {
backStyle = new GUIStyle(GUI.skin.box);
backStyle.normal.background = MakeTex(2, 2, new Color(0f, 0f, 0f, 1f));
}
}
Texture2D MakeTex(int width, int height, Color col) {
Color[] pix = new Color[width * height];
for (int i = 0; i < pix.Length; i++) {
pix[i] = col;
}
Texture2D result = new Texture2D(width, height);
result.SetPixels(pix);
result.Apply();
return result;
}
}
サーフェースシェーダでの「IN.screenPos.w」
いくつかのシェーダを見ていて以下の記述があることに気づく。
float2 screenUV = IN.screenPos.xy / IN.screenPos.w;
どうやらこれは、スクリーン座標を 0.0~1.0
に簡単に正規化する方法らしい。
要は要素として余った w
に、正規化を手助けするための数値が予め入っているからそれを使おう的な話だと思う。
Gizmoを表示する
選択されたときなどに、Gizmoをカスタムで表示させたりすることができる。
具体的には以下のスクリプトをアタッチすると表示される。
public class Gizmo : MonoBehaviour
{
[SerializeField]
float _gizmoSize = 0.3f;
[SerializeField]
Color _gizmoColor = Color.yellow;
void OnDrawGizmoSelected()
{
Gizmos.color = _gizmoColor;
Gizmos.DrawWireSphere(transform.position, _gizmoSize);
}
}
例ではSphereを表示するものだけど、他にもいくつか種類がある。
(詳細はドキュメントを参照)
Logに色をつけたりフォーマットを適用する
Debug.LogFormat("<color=green>{0}</color>", gameObject.name);