本日はUnity枠です。
今回はUnityのシーン上に配置した3Dモデルの持つポリゴン数をより分かりやすく表示するためにシーン上にギズモとしてポリゴン数を表示する機能を作っていきます。
〇ポリゴン数の取得
ポリゴン数はmeshFilterコンポーネントのtriangles.Lengthを3で割ることで取得できます。
int polygonCount = meshFilter.sharedMesh.triangles.Length / 3;
Unityのエディタで選択中のオブジェクトは以下のように取得できます。
GameObject selectedObject = Selection.activeGameObject;
現在選択しているアクティブなメッシュからポリゴン数を取得するに配下のようなコードになります。
if (Selection.activeGameObject != null) { GameObject selectedObject = Selection.activeGameObject; MeshFilter meshFilter = selectedObject.GetComponent<MeshFilter>(); if (meshFilter != null) { int polygonCount = meshFilter.sharedMesh.triangles.Length / 3; } }
最後にGUIのギズモを表示します。 UnityのEditor拡張ではHandles.BeginGUI~Handles.EndGUIを使用します。 以下のようになります。
if (meshFilter != null) { int polygonCount = meshFilter.sharedMesh.triangles.Length / 3; Handles.BeginGUI(); GUILayout.Label("Polygon Count: " + polygonCount); Handles.EndGUI(); }
シーンウィンドウに表示するためにはOnSceneGUIを使用します。
static void OnSceneGUI(SceneView sceneView) { }
これによって選択中のオブジェクトのポリゴン数がシーンウィンドウの上部に表示されるようになります。
〇コード全文
using UnityEngine; using UnityEditor; [InitializeOnLoad] public class PolygonCounter { static PolygonCounter() { SceneView.onSceneGUIDelegate += OnSceneGUI; } static 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; Handles.BeginGUI(); GUILayout.Label("Polygon Count: " + polygonCount); Handles.EndGUI(); } } } }