当前位置:网站首页>Unity editor extended UI control
Unity editor extended UI control
2022-07-05 20:11:00 【Ling'er of heart】
Shake ahead : Recognize the necessity of Editor Extension
For a variety of reasons , Whether mobile terminal or host /PC End , In recent years, the volume of games released has become larger and larger . Generally speaking, a large amount of game development needs a very mature and perfect workflow , Or have a strong ability to industrialize , image R Game manufacturers like Ubisoft star will certainly have a very strong industrial capacity , Can there be such a large number of details as the big cousin or the assassin's Creed BUG, slip of tongue , It is a game work with continuous iteration
It is said that if a worker wants to do good things, he must first sharpen his tools , To improve the efficiency of game development , It is necessary to have useful game development tools , In the end, we can't get around the game development engine
The game industry often says , Self developed engines are not necessarily the best , But the best engine must be self-developed , To some extent, it shows the advantages of customized engine . Though like Unity The business engine like fantasy is very mature and easy to use , But it is still a general commodity , It is difficult to achieve good adaptability in every aspect
And just Unity engine , Compared with illusion, it is not mature enough in the whole workflow . There are still a lot of programmers thinking about the operation mode and usage habits , The visualization of many development tools is not perfect , It may not be a big problem for programmers , But it is very unfriendly to planning and Art
On all levels , In order to improve the operability of the editor and ensure the uniqueness of project development , And expand the editor , It has become one of the necessary skills for game developers
happen :Unity Editor Extension UI Control
After the messy words , Return to the right topic . according to Unity Explanation of documents and cases , Understand the structure and method required for the creation process of editor interface
Play games with UI The interface is different , There is no ready-made control for visual construction of engine editor interface , And can only rely on the lower level of code commands to complete . But fortunately, Unity Provides a complete set of pure code interface editing mode , And call it “ Instant mode ”GUI System . For the specific explanation of the system, here is the description of directly handling official documents :
- “ Instant mode ”
GUISystem ( Also known asIMGUI) It is a completely independent functional system , differUnityGame object based master UI System .IMGUIIs a code drivenGUISystem , Mainly used as a tool for programmers
Although the system is related to the master UI The system is different , But it also shares the same root , It is not difficult to learn . Through a small Demo To demonstrate IMGUI Specific use methods and some points that should be paid attention to
Inherit EditorWindow Create editor window :
Editor UI Interface display and logic refresh are generally inherited from EditorWindow This class to achieve , The use of its lifecycle structure is similar to inheritance through editing MonoBehavior The script code of completes the implementation of the game life cycle logic . Both have similar monitoring events , The same periodic refresh method , So it can be used successfully without learning
stay Unity Created in and inherited from EditorWindow Class editor script and name it EditorDemo , Then use GetWindow Method creation CreateWindow Static methods ( Note that it must be static ), Initialize the editor window interface through this static method , The specific code details are as follows :
public class EditorDemo : EditorWindow
{
[MenuItem("EditorDemo/Test &1")]
public static EditorDemo CreateWindow()
{
EditorDemo window = GetWindow<EditorDemo>(" Test Editor ");
window.autoRepaintOnSceneChange = true;
window.Show();
return window;
}
}
In the code above , Will be added to the initialization static method MenuItem The command is used to add an open tab of the user-defined editor in the upper navigation bar of the engine
- About MenuItem:
MenuItemProperty is used to add menu items to the main menu and the inspector context menu , Using a specific format can achieve some additional effects , For example, using the backslash symbol in the above case can create multiple levels of menus , and “&” Symbol can add an opening shortcut key to the editor interface ( Usually withAltForm combined key ), As shown in the figure :

After initializing the editor interface , The following interface details need to be correct EditorWindow Class to do some understanding . Consult the documentation to familiarize yourself with some of the message functions provided by this class . Understand which editor functions they use to implement in different states :
The message above , Extend the editor UI Aspects that need the most attention OnGUI function , Generally speaking , The creation of interface elements usually needs to be written into the modification method . We talked about instant mode before GUI Create editor UI Control cannot be completed by visual operation tools , Only by Unity Related to the offer API To do it , The process is similar to not using a game development engine , Game development directly based on the corresponding programming language , Common control creation classes include the following :
GUI: yesUnityEngineNext class , The method can be found inRuntimeState call executionGUILayout:GUIAuto typesetting version of , There is no need toRectLayout orientationEditorGUI: yesUnityEditorEditor class underEditorGUILayout:EditorGUIAuto typesetting version of , There is no need toRectLayout orientation
Through the naming of the four classes, it is also easy to see the differences and use intervals between them . Generally speaking ,GUI And GUILayout Is the most widely used , Editor status and RunTime Available under . Independent editing windows are usually GUI And EditorGUI The two classes can be mixed , When used in the running state, it can only be used GUI or GUIlayerout
Use more scenes GUIlayout Case study , You can see from the document introduction Unity The engine provides quite a few interfaces for creating controls , Be familiar with using these interfaces , You can easily develop the required editor by using your own game interface development interface

Introduce these through a simple case API How to use . Try to select an object in the scene , And through the editor to control its overall scaling and color change :
First, about the acquisition of selected objects ,Unity It provides the method of getting the object editor selected by the developer in the editor state Selection.activeGameObject, And in the front about EditorWindow In the message of OnSelectionChange function , This function will be called when the selection object changes . By using these two functions and interfaces, we can efficiently get the objects selected in real time :
public GameObject selectObj;
private void OnSelectionChange()
{
selectObj = Selection.activeGameObject;
}
After getting an object in the editor scene , Usually we can adjust Inspector The corresponding parameters in the panel can change the state of the selected object . The following code is an editor control to simulate this effect :
public string selectName;
public string textStr;
public float slideNum;
public Color color;
private void OnGUI()
{
selectName = selectObj == null ? " No object selected " : selectObj.name;
selectName = EditorGUILayout.TextField(" Name of the selected object :", selectName);
GUILayout.Space(20);
slideNum = EditorGUILayout.Slider(" Control object scaling :", slideNum, 1, 10);
if (selectObj!=null)
{
selectObj.transform.localScale=new Vector3(slideNum,slideNum,slideNum);
}
GUILayout.Space(20);
color = EditorGUILayout.ColorField(" Choose a color :",color);
GUILayout.Space(10);
if (GUILayout.Button(" Click change color ")&&selectObj != null)
{
selectObj.GetComponent<MeshRenderer>().material.color = color;
}
}
Demonstration effect :
Inspector Script component extension of panel :
Sometimes some extension requirements do not need to be completed through a separate window , For example, some lightweight editing operations are required for some script components , You can do some embedded method extensions
Simply make a case demonstration . First create an inheritance On MonoBehavior Script and mount it to the object in the scene , Then write a method to fill the string with data in the script :
public class Demo : MonoBehaviour
{
public string str;
public void ChangeStrDemo()
{
str = " Editor extension test ";
}
}
Then create one that inherits from Editor Editor extension class , 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(" Test button "))
{
demo.ChangeStrDemo();
}
}
}
Finish the above code and return to the engine , You can get a method of executing functions in the editor

Small Tip:
There are many ways to execute functions in editor state , Such as the simplest commonly used
ContextMenucommand . By adding commands to script functions , You can quickly call methods in the editor class , And with theRuntimeDifferent modes , This method will save the modified status , It is very suitable for rapid development and expansion
Runtime In mode Game Window expansion :
Runtime In mode, you can MonoBehavior Call directly in the script GUI Method to expand , Simply state the process through a case :
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, " Test the small window ");
}
void CreateGuiWindow(int id)
{
if (GUILayout.Button(" open asset Folder and filter files "))
{
EditorUtility.OpenFilePanel(" Select File ", Application.dataPath,"cs");
}
if (GUILayout.Button(" open asset Folder select Folder "))
{
EditorUtility.OpenFolderPanel(" Select the folder ", Application.dataPath, "");
}
}
}
Execute the above code , The effect is as follows :
because Runtime In mode Game Window extensions are usually implemented based on their own project structure , Therefore, it is not very appropriate to use the above case to understand its use mode , However, this mode is not often used , A little understanding of its control usage
although Runtime Editor extensions in mode are not often used to , But compared to Editor The state has a higher degree of freedom , It can execute many methods and functions that can be adjusted only in the running state , Or it can better interact with the framework content of the current project . Without extra j Turn it into an editor method , This may be very efficient for some small function extensions
UI Control collection :
Concrete UI Control can be obtained by consulting the document , The link address is as follows :
GUILayout: Click to go toGUI: Click to go toEditorGUILayout: Click to go toEditorGUI: Click to go to
For convenience of repeated reference , Here is also a brief list of some commonly used :
EditorGUILayout:
TextArea: Create a text area
TextField: Create a text field
IntField And FloatField: Digital 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 for input Bounds Of Center and Extents Field .
ColorField: Color selector
Toggle: Create a switch
RectField Create for input Rect Of X、Y、W and H Field
EditorToolbar: Create a toolbar filled with the specified set of editor tools
EnumFlagsField: After clicking , The system will display a menu with options for each value of the enumeration type
EnumPopup: Create an enumeration pop-up selection field
IntSlider: Create a slider , The user can drag to change the integer value between the minimum value and the maximum value
Foldout: Create a label with a folded arrow on the left
HelpBox: Create a help box with a message sent to the user
InspectorTitlebar: Create a similar to Inspector Title bar of the window
LayerField: Create a layer selection field
TagField: Create a label selection field
PasswordField: Create a text field that allows users to enter passwords .
Back shake : Editor extension function preview
The above introduces some basic editor interface construction related UI Control , It explains some basic knowledge . Besides the interface, editor extensions , Another important part is the implementation of Editor Extension editing function . Like above Runtime Small case of opening local folder in case , It is the embodiment of editing function in Editor Extension , adopt UI Control maintenance triggers these auxiliary functions to improve development efficiency, which is the core of the extension
In order to make the content introduction of Editor Extension more complete , I will try to update the next article as soon as possible , Of course, the most important thing is , If a boss finds any problems in the article , I hope you can leave a message indicating , I will strive to improve it in the follow-up
边栏推荐
- After 95, Alibaba P7 published the payroll: it's really fragrant to make up this
- Hong Kong stocks will welcome the "best ten yuan store". Can famous creative products break through through the IPO?
- 【数字IC验证快速入门】6、Questasim 快速上手使用(以全加器设计与验证为例)
- Build your own website (16)
- S7-200smart uses V90 Modbus communication control library to control the specific methods and steps of V90 servo
- Scala基础【HelloWorld代码解析,变量和标识符】
- 挖财钱堂教育靠谱安全吗?
- Go language | 02 for loop and the use of common functions
- Wechat applet regular expression extraction link
- Base du réseau neuronal de convolution d'apprentissage profond (CNN)
猜你喜欢

S7-200smart uses V90 Modbus communication control library to control the specific methods and steps of V90 servo

Hong Kong stocks will welcome the "best ten yuan store". Can famous creative products break through through the IPO?

Guidelines for application of Shenzhen green and low carbon industry support plan in 2023

基础篇——配置文件解析

Leetcode: binary tree 15 (find the value in the lower left corner of the tree)

Let's talk about threadlocalinsecurerandom

leetcode刷题:二叉树10(完全二叉树的节点个数)

Zero cloud new UI design

深度学习 卷积神经网络(CNN)基础

JVMRandom不可设置种子|问题追溯|源码追溯
随机推荐
C - sequential structure
淺淺的談一下ThreadLocalInsecureRandom
函数的概念及语法
点云文件的.dat文件读取保存
ACM getting started Day1
【数字IC验证快速入门】7、验证岗位中必备的数字电路基础知识(含常见面试题)
Leetcode brush question: binary tree 14 (sum of left leaves)
处理文件和目录名
Unity编辑器扩展 UI控件篇
A solution to PHP's inability to convert strings into JSON
挖财钱堂教育靠谱安全吗?
Debezium series: PostgreSQL loads the correct last submission LSN from the offset
c——顺序结构
leetcode刷题:二叉树13(相同的树)
图嵌入Graph embedding学习笔记
C language OJ gets PE, OJ of ACM introduction~
CADD课程学习(7)-- 模拟靶点和小分子相互作用 (半柔性对接 AutoDock)
Flume series: interceptor filtering data
Leetcode skimming: binary tree 10 (number of nodes of a complete binary tree)
实操演示:产研团队如何高效构建需求工作流?