本日はUnity枠です。
昨日はunityのシーンビューで現在選択中のメッシュのポリゴン数が表示されるような機能を作りました。
こちらの問題として一度エディタウィンドウを立ちげ設定を行い、閉じて再度エディタウィンドウを立ち上げた場合次の画像のよう2重にカウンター機能が有効になってしまうことです。

今回はウィンドウを閉じる際にイベントを発火させて終了の処理を行います。
〇EditorWindowを閉じる際のイベント
Unityではエディタウィンドウを閉じる際にOnDestroyメソッドを使用することでイベントを取得できます。
void OnDestroy()
{
Debug.Log("Editor Window is being closed");
}
このメソッドをエディタウィンドウのコードに加えて開いたウィンドウを閉じることで次のようにきちんとログが出力されていることを確認できました。

今回は次のように処理を加えることでウィンドウを閉じた際に初期化を行うことができます。
void OnDestroy()
{
if (isSceneViewRegistered)
{
SceneView.onSceneGUIDelegate -= OnSceneGUI;
isSceneViewRegistered = false;
}
}

以上でUIの重複は行われなくなりました。
〇コード全文
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();
}
}
}
void OnDestroy()
{
if (isSceneViewRegistered)
{
SceneView.onSceneGUIDelegate -= OnSceneGUI;
isSceneViewRegistered = false;
}
}
}