Unity Editor Extended UI Controls

Front Shake: Recognizing the Necessity of Editor Extensions

Due to various reasons, whether it is the mobile terminal or the console/PC terminal, the volume of games released in the past few years is getting bigger and bigger. Generally speaking, large-scale game development requires a very mature and complete workflow, or strong industrialization capabilities. Game manufacturers like Rockstar Ubisoft must have very strong industrialization capabilities in order to have a large Cousin is full of a lot of details or Assassin's Creed is full of BUGs and slips of the tongue, it is a game that continues to iterate

The so-called good work must first sharpen its tools. If you want to improve the efficiency of game development, you must have useful game development tools. In the end, you cannot bypass the game development engine.

It is often said in the game industry that self-developed engines are not necessarily the best, but the best engines must be self-developed, which to a certain extent shows the advantages of customized engines. Although commercial engines like Unity and Unreal are very mature and easy to use, they are still general-purpose commodities, and it is difficult to achieve good adaptability in every aspect

As for the Unity engine, compared to Unreal, its performance in the entire workflow is not mature enough. There are still a lot of programmers’ thoughts in the usage habits of operation methods, and the visualization of many development tools is not perfect enough. It may not be a big problem for programmers, but it is very unfriendly for planning and art.

On various levels, in order to improve the ease of operation of the editor and ensure the uniqueness of project development, the expansion and modification of the editor has become one of the necessary skills for game developers

Occurrence: UI control of Unity editor extension

After finishing the nonsense, return to the topic. According to the explanations and cases of the Unity documentation, understand the structure and methods required for the editor interface creation process

Different from the game UI interface, the construction of the engine editor interface has no ready-made controls for visual construction, but can only be completed by hand with lower-level code commands. Fortunately, Unityit provides a complete set of pure code interface editing mode, which is called "immediate mode" GUI system. For a specific explanation of the system, here is a description of the official document:

  • The "immediate mode" GUI system (as it's called IMGUI) is a completely separate functional system from the main game object Unitybased UI system. IMGUIis a code-driven GUIsystem primarily used as a tool for programmers

Although this system UIis not quite the same as the main system, it has the same root and is not difficult to learn. The specific usage method and some points that should be paid attention to are Demodemonstrated through the following smallIMGUI

Inherit EditorWindow to create an editor window:

The editor interface display and logic refresh are generally implemented by UIinheriting from this class, and the use of its life cycle structure is similar to the realization of the game life cycle logic by editing the inherited script code. The two have similar monitoring events and the same periodic refresh method, so they can be used successfully without learningEditorWindowMonoBehavior

Create Unityand inherit from EditorWindowthe class editor script and name it EditorDemo, and then use the method in the class GetWindowto create CreateWindowa static method (note that it must be static), and use this static method to initialize the editor window interface. The specific code details are as follows:

public class EditorDemo : EditorWindow
{
    
    
    [MenuItem("EditorDemo/Test  &1")]
    public static EditorDemo CreateWindow()
    {
    
    
        EditorDemo window = GetWindow<EditorDemo>("测试编辑器");
        window.autoRepaintOnSceneChange = true;
        window.Show();
        return window;
    }
}

In the above code, MenuItema command will be added to the initialization static method to realize the opening tab of a custom editor in the upper navigation bar in the engine

  • About MenuItem:
    MenuItemThe attribute is used to add menu items to the main menu and the context menu of the inspection panel. Some additional effects can be achieved by using a specific format. For example, in the above case, the backslash symbol can be used to create a multi-level menu, while the "&" symbol is You can add a shortcut key (usually Alta combination key) to the editor interface , as shown in the figure:

insert image description here

After completing the initialization of the editor interface, the following interface details require EditorWindowsome understanding of the class. Consult the documentation to familiarize yourself with some of the message functions provided by this class below. Understand which editor functions they are used to implement in different states: In the above message, the functions that need the most attention in terms of
insert image description here
editor extensions , generally speaking, the creation of interface elements usually need to be written into the modification method. As mentioned above, the creation of editor controls in instant mode cannot be done through visual operation tools, and can only be done by the provided correlation . The process is similar to the game development directly based on the corresponding programming language without using the game development engine. Commonly used controls are created The classes are as follows:UIOnGUIGUIUIUnityAPI

  • GUI: is UnityEnginethe class below, its method can Runtimebe called and executed in the state
  • GUILayout: GUIan auto-typesetting version without Rectlayout positioning
  • EditorGUI: is UnityEditorthe editor class under
  • EditorGUILayout: EditorGUIan auto-typesetting version without Rectlayout positioning

It is also easy to see the differences and use intervals between them through the naming of the four classes. Generally speaking, GUIand GUILayoutare the most widely used, RunTimeboth editor state and next are available. The independent editing window EditorGUIcan usually be used in combination with the GUI and the two classes, but it can only be used in the running state GUIorGUIlayerout

Taking the case of many usage scenarios GUIlayout, you can see from the document introduction that the Unity engine provides quite a few interfaces for creating controls. If you are familiar with using these interfaces, you can use the development interface of your own game interface to easily develop the required editing device

insert image description here
Introduce how to use these through a simple case API. Try to select an object in the scene, and use the editor to control its overall zoom and color change:

First of all, regarding the acquisition of the selected object, Unity provides the method of obtaining the object editor selected by the developer in the editor state Selection.activeGameObject, and there is a function in the previous EditorWindowmessage about OnSelectionChangeit, which will be called when the selected object changes. Real-time selected objects can be obtained efficiently by using these two functions and interfaces:

    public GameObject selectObj;
    private void OnSelectionChange()
    {
    
    
        selectObj = Selection.activeGameObject;
    }

After obtaining an object in the editor scene, we can usually adjust Inspectorthe corresponding parameters in the panel to change the state of the selected object. The following code is an editor control to mimic this effect:

    public string selectName;
	public string textStr;
    public float slideNum;
    public Color color;
    private void OnGUI()
    {
    
    
        selectName = selectObj == null ? "未选中物体" : selectObj.name;
        selectName = EditorGUILayout.TextField("选中的物体名:", selectName);
        GUILayout.Space(20);
        slideNum = EditorGUILayout.Slider("控制对象缩放:", slideNum, 1, 10);
        if (selectObj!=null)
        {
    
    
            selectObj.transform.localScale=new Vector3(slideNum,slideNum,slideNum);
        }
        GUILayout.Space(20);
        color = EditorGUILayout.ColorField("选择颜色:",color);
        GUILayout.Space(10);
        if (GUILayout.Button("点击更换颜色")&&selectObj != null)
        {
    
    
            selectObj.GetComponent<MeshRenderer>().material.color = color;
        }
    }

Demonstration effect:
Please add a picture description

Script component extension of the Inspector panel:

Sometimes some extension requirements do not need to be completed through an independent window. For example, if you want some light editing operations for some script components, you can do some embedded method extensions

Simply make a case presentation. First create an inheritance 于MonoBehaviorscript and mount it on the objects in the scene, and then write a method to fill the string with data in the script:

public class Demo : MonoBehaviour
{
    
    
    public string  str;
    public void ChangeStrDemo()
    {
    
    
        str = "编辑器扩展测试";
    }
}

Then create an Editoreditor extension class inherited from, the code is as follows:

[CustomEditor(typeof(Demo))]
class EditorInspectorDemo : Editor
{
    
    
    public Demo demo;
    private void Awake()
    {
    
    
        demo = target as Demo;
    }
    public override void OnInspectorGUI()
    {
    
    
        base.OnInspectorGUI();
        if(GUILayout.Button("测试按钮"))
        {
    
    
            demo.ChangeStrDemo();
        }
    }
}

After completing the above code and returning to the engine, you can get a method to execute the function in the editor

Please add a picture description

Little Tip:

There are many ways to execute function methods in the editor state, such as the simplest common ContextMenucommands. By adding commands to the script function, you can quickly call the method in the editor class, and unlike the Runtimemode, this method will save the modified state, which is very suitable for rapid development and extension

Game window extension in Runtime mode:

In Runtime mode, methods can MonoBehaviorbe directly called in scripts GUIfor extension. A case is used to briefly state the process:

Get the event response control ( ) by creating an in-game window Button, and implement an editor method: record the resource path to open the file in the specified file directory:

public class Demo : MonoBehaviour
{
    
    
    private void OnGUI()
    {
    
    
        GUI.Window(908, new Rect(0, 0, 300, 300), CreateGuiWindow, "测试小窗口");
    }
    void CreateGuiWindow(int id)
    {
    
    
        if (GUILayout.Button("打开asset文件夹并筛选文件"))
        {
    
    
            EditorUtility.OpenFilePanel("选择文件", Application.dataPath,"cs");            
        }
        if (GUILayout.Button("打开asset文件夹选择文件夹"))
        {
    
    
             EditorUtility.OpenFolderPanel("选择文件夹", Application.dataPath, "");
        }       
    }
}

Execute the above code, the effect is as follows:
Please add a picture description

Since the window extension Runtimein the mode Gameis usually executed based on the mode of its own project structure, it is not very appropriate to use the above case to understand its usage mode, but this mode is not often used, just understand the usage of its controls a little

Although the editor extension is not commonly used in the mode, it has a higher degree of freedom than the state, and can execute many method functions that can only be called in the running state, or can better interact with the framework content of the current Runtimeproject Editor. Instead of turning it into an editor method, it may be very efficient for some small function extensions

Small collection of UI controls:

The specific UI controls can be obtained by consulting the document, the link address is as follows:

For the convenience of repeated reference, here is a brief list of some commonly used ones:

EditorGUILayout:

  • TextArea: Create a text area

  • TextField: Create a text field

  • IntField and FloatField: Number input box

  • Vector2Field and Vector3Field, etc.: vector input box

  • ObjectField: Generate a field that can accept any object type

  • Space: Leave a small space between the previous control and the next control.

  • BoundsField: Create Center and Extents fields for entering Bounds.

  • ColorField: color picker

  • Toggle: Create a Switch

  • RectField creates X, Y, W, and H fields for input to a Rect

  • EditorToolbar: Creates a toolbar populated with the specified set of editor tools

  • EnumFlagsField: When clicked, a menu with options is displayed for each value of the enum type

  • EnumPopup: Creates an enumeration popup select field

  • IntSlider: Creates a slider that the user can drag to change an integer value between a minimum and a maximum

  • Foldout: Creates a label with a foldout arrow on the left

  • HelpBox: Creates a help box with a message sent to the user

  • InspectorTitlebar: Creates a title bar similar to the Inspector window

  • LayerField: Create a layer selection field

  • TagField: Create a tag selection field

  • PasswordField: Creates a text field where the user can enter a password.

Post-Shake: Editor Extended Features Trailer

The above introduces some basic editor interface construction related UI controls, which can be regarded as illustrating some basic knowledge. In addition to the interface of the editor extension, another important thing is the realization of the editing function of the editor extension. For Runtimeexample, the small case of opening a local folder in the above case is the embodiment of the editing function in the editor extension. The core of the extension is to trigger these auxiliary functions that improve development efficiency through UI control maintenance.

In order to make the content introduction of the editor extension more complete, I will try my best to update the next article as soon as possible. Of course, the most important thing is that if anyone finds any problems in the article, I hope you can leave a message and point it out. I will work hard to improve it in the future.

Guess you like

Origin blog.csdn.net/xinzhilinger/article/details/125462320