SceneView 에디터 툴 그리기

in #kr5 years ago (edited)

인스펙터에도 띄워보고, 팝업 윈도우에도 해보고

하지만 씬뷰에 상시 떠있는 쪽이 편리하더군요.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

#if UNITY_EDITOR
using UnityEditor;
using UnityEditorInternal;
[ExecuteInEditMode]
#endif

public class TestScene : MonoBehaviour
{
#if UNITY_EDITOR
    private void OnEnable()
    {
        TestSceneEditor.Instance.Init(this, 20, 20, 250, 250);
    }

    private void OnDisable()
    {
        TestSceneEditor.Instance.Exit();
    }
#endif
}

#if UNITY_EDITOR
public class TestSceneEditor
{
    public enum EAnchor
    {
        L_Top = 0,
        R_Top,
        L_Bottom,
        R_Bottom
    }

    public static TestSceneEditor Instance
    {
        get
        {   
            if (m_instance == null)
            {
                m_instance = new TestSceneEditor();
            }
            return m_instance;
        }
    }

    public static TestSceneEditor m_instance;
    public static Vector2 Scroll;
    public static TestScene TargetScript;
    private static Vector2 Pos = new Vector2(20, 20);
    private static Vector2 Size = new Vector2(250, 200);
    private static int Anchor = 0;

    public void Init(TestScene script, float x, float y, float width, float height, int anchor = 0)
    {
        TargetScript = script;

        Pos = new Vector2(x, y);
        Size = new Vector2(width, height);
        Anchor = anchor;

        SceneView.onSceneGUIDelegate += OnSceneGUI;
    }

    public void Exit()
    {
        SceneView.onSceneGUIDelegate -= OnSceneGUI;
    }

    static void OnSceneGUI(SceneView scn)
    {
        if (Event.current.type != EventType.Repaint)
        {
            int controlId = GUIUtility.GetControlID(FocusType.Passive);
           GUILayout.Window(controlId, CreateRect(scn, Pos, Size, Anchor), OnDisplay, "Editor");
        }
    }

    static void OnDisplay(int id)
    {
        Scroll = GUILayout.BeginScrollView(Scroll);

        EditorGUILayout.LabelField("Label");

        if (GUILayout.Button("Button"))
        {
        }

        GUILayout.EndScrollView();
    }
    
    private static Rect CreateRect(SceneView scn, Vector2 pos, Vector2 size, int anchor)
    {
        Vector2 rc = new Vector2(pos.x, pos.y);
        if (scn != null)
        {
            switch ((EAnchor)anchor)
            {
                case EAnchor.L_Top: rc = new Vector2(pos.x, pos.y); break;
                case EAnchor.R_Top: rc = new Vector2(scn.camera.pixelRect.width - pos.x, pos.y); break;
                case EAnchor.L_Bottom: rc = new Vector2(pos.x, scn.camera.pixelRect.height - pos.y); break;
                case EAnchor.R_Bottom: rc = new Vector2(scn.camera.pixelRect.width - pos.x, scn.camera.pixelRect.height - pos.y); break;
            }
        }
        return new Rect(rc.x, rc.y, size.x, size.y);
    }
}
#endif

nimiq.png