前提:需要在窗口监听事件

[ InitializeOnLoadMethod ]

作用及描述:允许在 Unity 加载时初始化编辑器类方法,无需用户操作。(初始化时调用)
=>的作用:https://blog.csdn.net/qq_40544338/article/details/103599590

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEditor;
  5. public class TestScene : MonoBehaviour
  6. {
  7. //使用SceneView类
  8. [InitializeOnLoadMethod]
  9. static void IntiallizeOnLoad()
  10. {
  11. UnityEditor.SceneView.duringSceneGui += (sceneView) =>
  12. {
  13. if (Event.current != null && Event.current.button == 1 && Event.current.type == EventType.MouseUp)
  14. {
  15. Debug.Log("鼠标抬起");
  16. Rect position = new Rect(Event.current.mousePosition.x,Event.current.mousePosition.y-100, 100, 100);
  17. GUIContent[] contents = new GUIContent[] { new GUIContent("Test1"), new GUIContent("Test2") };
  18. EditorUtility.DisplayCustomMenu(position, contents,-1,(data,opt,select) => {
  19. Debug.LogFormat("data:{0},opt:{1},select:{2},value:{3}", data, opt, select, opt[select]);
  20. },null);
  21. Event.current.Use();
  22. }
  23. };
  24. }
  25. }

Scene视图Gizoms

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class TestSceneGizmos : MonoBehaviour
  5. {
  6. //在Editor一般不编译,所以需要将文件转移到其他地方
  7. //实现场景中绘制内容
  8. public Color color;
  9. #if UNITY_EDITOR //只能在Editor编译
  10. private void OnDrawGizmosSelected()//仅选中绘制
  11. {
  12. Gizmos.color = color;
  13. Gizmos.DrawLine(transform.position, transform.position + Vector3.up);
  14. Gizmos.DrawSphere(transform.position, 1);
  15. }
  16. private void OnDrawGizmos()//不选中也绘制
  17. {
  18. Gizmos.DrawIcon(transform.position, "Assets/Texture/logo.png");
  19. }
  20. #endif
  21. }

Scene视图添加UI

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEditor;
  5. [CustomEditor(typeof(TestSceneGizmos))]
  6. public class TestSceneGUI : Editor
  7. {
  8. private void OnSceneGUI()
  9. {
  10. Handles.BeginGUI();
  11. if (GUILayout.Button("Click Here",GUILayout.Width(100) ))
  12. {
  13. Debug.Log(target.name);
  14. }
  15. GUILayout.Label(target.name);
  16. Handles.EndGUI();
  17. }
  18. }

image.png

Scene常驻UI

  1. [InitializeOnLoadMethod]
  2. static void InitializeOnLoad()
  3. {
  4. SceneView.duringSceneGui += (sceneView) =>
  5. {
  6. Handles.BeginGUI();
  7. if(GUILayout.Button("test2",GUILayout.Width(200))){
  8. Debug.Log("test2");
  9. }
  10. GUILayout.Label("固定UI");
  11. Handles.EndGUI();
  12. };
  13. }

image.png