本日はUnity枠です。
先日はポリゴン数をシーンウィンドウのビューポート上でテキストとして表示しました。
しかし前回までの内容では常に表示されており、ビューポートの使い勝手が普段と変わってしまいますので今回は任意のタイミングでオンオフできるようにしていきます。
〇EditorWindow
今回はEditorWindowを使用した方法を行います。
EditorWindowはUnityのウィンドウとして使用できるエディタの拡張になります。

EditorWindowを使用するためにはEditorWindowクラスから継承したクラスを作成します。
public class PolygonCounter : EditorWindow
{
}
実行したいメソッドにMenuItem("コマンドの場所")のアトリビュートを付けます。
またOnGUIメソッドで表示されるウィンドウのUIを記述します。
今回は以下のように記述しました。
[MenuItem("Window/Polygon Counter")]
static void Init()
{
//ウィンドウを開く
PolygonCounter window = GetWindow<PolygonCounter>();
window.titleContent = new GUIContent("Polygon Counter");
//表示するUIの初期値
style = new GUIStyle();
style.fontStyle = FontStyle.Bold;
style.fontSize = 14;
}
//UI
void OnGUI()
{
EditorGUILayout.Space(10);
//チェックボックス
showPolygonCount = EditorGUILayout.Toggle("Show Polygon Count", showPolygonCount);
if (showPolygonCount && !isSceneViewRegistered)
{
SceneView.onSceneGUIDelegate += OnSceneGUI;
isSceneViewRegistered = true;
}
else if (!showPolygonCount && isSceneViewRegistered)
{
SceneView.onSceneGUIDelegate -= OnSceneGUI;
isSceneViewRegistered = false;
}
}
最後に今まで作成したポリゴンを表示する機能をOnSceneGUI(SceneView sceneView)としてメソッド内に記述します。
これによってウィンドウを開きShow Polygon Countを有効にした際にシーンビューにポリゴン数が表示されるようになります。

本日は以上です。
〇コード全文
using UnityEngine;
using UnityEditor;
public class PolygonCounter : EditorWindow
{
static GUIStyle style;
static Color normalColor = Color.white; // 通常の文字色
static Color highPolyColor = Color.yellow; // ポリゴン数が1000以上の場合の文字色
private bool showPolygonCount = true; // ポリゴン数の表示を有効にするかどうかのフラグ
private bool isSceneViewRegistered = false; // SceneView.onSceneGUIDelegateが登録されているかどうかのフラグ
[MenuItem("Window/Polygon Counter")]
static void Init()
{
PolygonCounter window = GetWindow<PolygonCounter>();
window.titleContent = new GUIContent("Polygon Counter");
style = new GUIStyle();
style.fontStyle = FontStyle.Bold;
style.fontSize = 14;
}
void OnGUI()
{
EditorGUILayout.Space(10);
showPolygonCount = EditorGUILayout.Toggle("Show Polygon Count", showPolygonCount);
if (showPolygonCount && !isSceneViewRegistered)
{
SceneView.onSceneGUIDelegate += OnSceneGUI;
isSceneViewRegistered = true;
}
else if (!showPolygonCount && isSceneViewRegistered)
{
SceneView.onSceneGUIDelegate -= OnSceneGUI;
isSceneViewRegistered = false;
}
}
void OnSceneGUI(SceneView sceneView)
{
if (Selection.activeGameObject != null)
{
GameObject selectedObject = Selection.activeGameObject;
MeshFilter meshFilter = selectedObject.GetComponent<MeshFilter>();
if (meshFilter != null)
{
int polygonCount = meshFilter.sharedMesh.triangles.Length / 3;
style.normal.textColor = polygonCount >= 1000 ? highPolyColor : normalColor;
Handles.BeginGUI();
GUILayout.Label("Polygon Count: " + polygonCount, style);
Handles.EndGUI();
}
}
}
}