unity 之AdvanceEditor 之Extending the Editor

mac2025-09-22  38

Editor Windows

 你可以创建自己的窗口,就像属性面板,场景窗口

创建自己的窗口需要遵循以下步骤:

常见一个脚本继承自 EditorWindow.使用代码触发窗口来显示自身。 使用gui代码实现功能

脚本必须在 “Editor”文件夹下.创建一个脚本继承自 EditorWindow. 在 OnGUI函数里面编写对应的功能脚本

using UnityEngine; using UnityEditor; using System.Collections; public class Example : EditorWindow { void OnGUI () { // The actual window code goes here } }

 

Showing the window

通过 MenuItem属性来来定义一个打开窗口的开关

通过EditorWindow.GetWindow 来显示窗口:

using UnityEngine; using UnityEditor; using System.Collections; class MyWindow : EditorWindow { [MenuItem ("Window/My Window")] public static void ShowWindow () { EditorWindow.GetWindow(typeof(MyWindow)); } void OnGUI () { // The actual window code goes here } }

Showing the MyWindow

可以使用 GetWindowWithRect  对窗口进行更多的操作

Implementing Your Window’s GUI

使用 (GUI 或者 GUILayout)给窗口布局.  EditorGUI and EditorGUILayout仅限编辑器窗口中的ui,

The following C# code shows how you can add GUI elements to your custom EditorWindow:

using UnityEditor; using UnityEngine; public class MyWindow : EditorWindow { string myString = "Hello World"; bool groupEnabled; bool myBool = true; float myFloat = 1.23f; // Add menu item named "My Window" to the Window menu [MenuItem("Window/My Window")] public static void ShowWindow() { //Show existing window instance. If one doesn't exist, make one. EditorWindow.GetWindow(typeof(MyWindow)); } void OnGUI() { GUILayout.Label ("Base Settings", EditorStyles.boldLabel); myString = EditorGUILayout.TextField ("Text Field", myString); groupEnabled = EditorGUILayout.BeginToggleGroup ("Optional Settings", groupEnabled); myBool = EditorGUILayout.Toggle ("Toggle", myBool); myFloat = EditorGUILayout.Slider ("Slider", myFloat, -3, 3); EditorGUILayout.EndToggleGroup (); } }

This example results in a window which looks like this:

 

Running Editor Script Code on Launch

有时候你想发布之后的应用运行编辑器状态下的脚本,你可以为一个类添加InitializeOnLoad 属性,执行它的构造方法,构造方法就是方法名和类名一样但是没有返回值

using UnityEngine; using UnityEditor; [InitializeOnLoad] public class Startup { static Startup() { Debug.Log("Up and running"); } }

比如在编辑器中设置一个常规回调。EditorApplication类有一个名为update的委托,该委托在编辑器运行时每秒调用多次。要在项目启动时启用此委托,可以使用如下代码:-

using UnityEditor; using UnityEngine; [InitializeOnLoad] class MyClass { static MyClass () { EditorApplication.update += Update; } static void Update () { Debug.Log("Updating"); } }
最新回复(0)