LoginSignup
5
6

More than 5 years have passed since last update.

特定条件を満たす場合にHierarchy上に画像を表示する

Last updated at Posted at 2017-02-08

機能

ヒエラルキー上に画像を表示するためのUnityエディタ拡張です。

サンプル

icon.png

使用用途

特定の条件を満たす場合(◯◯のフォントが設定されている時、特定のスクリプトがアタッチされている時など)に、Hierarchy上に画像を表示するための拡張機能です。

サンプルソースコード

ExampleEditorClass.cs
#region

using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

#endregion

/// <summary>
/// 特定の条件を満たす場合にHierarchy上に画像を表示する
/// </summary>
public static class ExampleEditorClass
{
    private const int IconSizeWidth = 16;

    private static Texture2D buttonImage;

    // Awakeよりも先に呼ばれる
    // https://anchan828.github.io/editor-manual/web/callbacks.html
    [InitializeOnLoadMethod]
    private static void Example()
    {
        EditorApplication.hierarchyWindowItemOnGUI += ExampleEditorClass.OnGui;
    }

    private static void OnGui(int instanceId, Rect selectionRect)
    {
        // Project全体からデータをロードできる(対象の画像がなければエラー)
        // http://kan-kikuchi.hatenablog.com/entry/AssetDatabase_LoadAsset
        ExampleEditorClass.buttonImage = AssetDatabase.LoadAssetAtPath("Assets/Image/img.png", typeof(Texture2D)) as Texture2D;

        // InstanceIDをオブジェクトに変換
        var gameObject = EditorUtility.InstanceIDToObject(instanceId) as GameObject;

        if (gameObject == null)
        {
            return;
        }

        // 探したい対象の処理(ex:イメージのRaycast)
        var imageObject = gameObject.GetComponent<Image>();

        if (!imageObject)
        {
            return;
        }

        var searchTarget = gameObject.GetComponent<Image>().raycastTarget;

        if (!searchTarget)
        {
            return;
        }

        // 画像の表示位置
        var imagePos = selectionRect;
        imagePos.x = imagePos.xMax - ExampleEditorClass.IconSizeWidth;
        imagePos.width = ExampleEditorClass.IconSizeWidth;

        // Inspector上に画像を表示する
        GUI.DrawTexture(imagePos, ExampleEditorClass.buttonImage);
    }
}

参考サイト、その他情報

コドモのころの夢
コガネブログ
エディタ拡張入門
kanのメモ帳

5
6
0

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
5
6