拓展自定义编辑器窗口(EditorGUILayout类)

原文地址:http://www.cnblogs.com/caymanlu/p/5722549.html

Unity支持自行创建窗口,也支持自定义窗口布局。在Project视图中创建一个Editor文件夹,在文件夹中再创建一条脚本。

自定义窗口需要让脚本继承EditorWindow再设置MenuItem,此时在Unity导航菜单栏中GameObjec->window就可创建一个自定义窗口。

0.窗口:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using  UnityEngine;
using  UnityEditor; //引入编辑器命名空间
publicclassMyEditor:EditorWindow
{
[MenuItem( "GameObject/caymanwindow" )]
staticvoidAddWindow()
{
//创建窗口
Rect wr =newRect(0,0,500,500);
//另一种方式:myEditor window = (myEditor)EditorWindow.GetWindow(typeof(myEditor), true, "cayman");
MyEditor window =(MyEditor)EditorWindow.GetWindowWithRect( typeof (MyEditor),wr, true , "widow name" );
window.Show();
}
     //[MenuItem("GameObject/caymanwindow", true)]   //如果没有选择物体,禁用菜单
    // static bool ValidateSelection() {
     //    return Selection.activeGameObject != null;
    // }
}
 
1.LabelField制作一个标签字段(通常用于显示只读信息)
LabelField(string label1,string label2,GUILayoutOption[] options)
//参数:label1标签字段前面的标签  label2显示在右侧的标签  options额外布局属性可选列表  --无返回值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
publicclass myEditor3 :EditorWindow{
//在编辑器显示一个标签,带有自编辑器开始的秒数
[MenuItem( "cayman/tempShow" )]
staticvoid newWelcome()
{
myEditor3 window3 =(myEditor3)EditorWindow.GetWindow( typeof (myEditor3), true , "Eam" );
window3.Show();
}
voidOnGUI()
{
EditorGUILayout.LabelField( "Time since start: " ,EditorApplication.timeSinceStartup.ToString());
this .Repaint(); //实时刷新
}
}

  

效果:
 
2.Toggle开关按钮
Toggle(bool value,GUILayoutOption[] options)
Toggle(string label,bool value,GUILayoutOption[] options)
//参数:label开关按钮前面的可选标签  value开关按钮的显示状态 options额外布局属性的可选列表  
//返回:bool,开关按钮的选择状态
复制代码
//如果开关控件被选择,显示一个按钮。
bool showBtn =true;
voidOnGUI()
{
showBtn =EditorGUILayout.Toggle("Show Button", showBtn);
if(showBtn)
{
if(GUILayout.Button("Close"))
this.Close();
}
}
复制代码

 

效果:
 
3.TextField文本字段
TextField(string text,GUILayoutOption[] options)                                  TextField(string label,string text,GUIStyle style,GUILayoutOption[] options)
TextField(string text,GUIStyle style,GUILayoutOption[] options)            TextField(GUIContent label,string text,GUILayoutOption[] options)
TextField(string label,string text,GUILayoutOption[] options)                 TextField( GUIContent label, string text,GUIStyle style,GUILayoutOption[] options)
//参数:label可选标签  text编辑的文本  style可选样式  options额外布局属性的可选列表
//返回:string,用户输入的文本
复制代码
  //通过字段,自动改变选择物体的名字
string objectName ="";
voidOnGUI()
{
GUILayout.Label("Select an object in the hierarchy view");
if(Selection.activeGameObject)
Selection.activeGameObject.name =EditorGUILayout.TextField("Object Name: ",Selection.activeGameObject.name);
this.Repaint();//实时刷新
}
}
复制代码
效果:
 
4.TextArea文本区域
TextArea(string text,GUILayoutOption[] options)
TextArea(string text,GUIStyle style,GUILayoutOption[] options)
//参数:text可编辑的文本  style可选样式 options额外布局属性的可选列表
//返回:string,用户输入的文本
复制代码
//在编辑器窗口可视化脚本,这可扩展保存脚本
string text ="Nothing Opened...";
TextAsset txtAsset;
Vector2 scroll;
voidOnGUI()
{
TextAsset newTxtAsset =EditorGUILayout.ObjectField("添加", txtAsset,typeof(TextAsset),true)asTextAsset;
if(newTxtAsset != txtAsset)
ReadTextAsset(newTxtAsset);
scroll =EditorGUILayout.BeginScrollView(scroll);
text =EditorGUILayout.TextArea(text,GUILayout.Height(position.height -30));
EditorGUILayout.EndScrollView();
}
voidReadTextAsset(TextAsset txt){
text = txt.text;
txtAsset = txt;
}
}
复制代码

 

效果:
 
5.SelectableLabel 可选择标签(通常用于显示只读信息,可以被复制粘贴
SelectableLabel(string text,GUILayoutOption[] options)
SelectableLabel(string text,GUIStyle style,GUILayoutOption[] options)
//参数:text显示的文本 style可选样式 options额外布局属性的可选列表   无返回值
string text="123";
voidOnGUI()
{
EditorGUILayout.SelectableLabel(text); //文本:可以选择然后复制粘贴
}
 
6.PasswordField 密码字段
PasswordField (string  password , GUILayoutOption[]  options )     PasswordField (string  password , GUIStyle style,  GUILayoutOption[]  options )
PasswordField (string label ,string password,GUILayoutOption[]  options )     PasswordField (string  password ,GUIStyle style,GUILayoutOption[]  options )
PasswordField (GUIContent label,string  password , GUILayoutOption[]  options )     PasswordField (GUIContent label,string password ,GUIStyle style,GUILayoutOption[]  options )
//参数:label开关按钮前面的可选标签  password编辑的密码  style可选样式   options指定额外布局属性的可选列表
//返回:string,用户输入的密码
 
复制代码
//创建密码字段并可视化在密码字段有什么键入。
string text ="Some text here";
function OnGUI(){
text =EditorGUILayout.PasswordField("Type Something:",text);
EditorGUILayout.LabelField("Written Text:", text);
}
}
复制代码

 

效果:
 
7.制作一个文本字段用于输入小数/整数。
FloatField 浮点数字段返回小数,由用户输入的值
 IntField    整数字段返回整数,由用户输入的值
1
2
3
4
5
6
7
8
int  clones=1;
voidOnGUI(){
clones=EditorGUILayout.IntField( "Number of clones:" , clones);
if (GUILayout.Button( "Clone!" ))
for ( var  i =0; i < clones; i++) //复制选择物体的次数。
Instantiate(Selection.activeGameObject,Vector3.zero,Quaternion.identity);
}
}

  

 
8.Slider 滑动条
--IntSlider 整数滑动条
MinMaxSlider 最小最大滑动条
Slider(float leftValue,float rightValue,GUILayoutOption[] options)
Slider(string label,float leftValue,float rightValue,GUILayoutOption[] options)
Slider(GUIContent label,float value,float leftValue,float rightValue,GUILayoutOption[] options)
//参数:label开关按钮前的可选标签  value编辑的值  leftValue滑动条最左边的值  rightValue滑动条最右边的值  options。。。
//返回:float,由用户设置的值
1
2
3
4
5
6
7
8
9
10
11
//缩放选择的游戏物体,在1-100之间
float  scale =0.0f;
voidOnGUI()
{
scale =EditorGUILayout.Slider(scale,1,100);
}
voidOnInspectorUpdate()
{
if (Selection.activeTransform)
Selection.activeTransform.localScale =newVector3(scale, scale, scale);
}

  

复制代码
//随机放置选择的物体在最小最大滑动条之间
float minVal =-10.0f;
float minLimit =-20.0f;
float maxVal =10.0f;
float maxLimit =20.0f;
voidOnGUI()
{
EditorGUILayout.LabelField("Min Val:", minVal.ToString());
EditorGUILayout.LabelField("Max Val:", maxVal.ToString());
EditorGUILayout.MinMaxSlider(ref minVal,ref maxVal, minLimit, maxLimit);
if(GUILayout.Button("Move!"))
PlaceRandomly();
}
voidPlaceRandomly()
{
if(Selection.activeTransform)
Selection.activeTransform.position =
newVector3(Random.Range(minVal, maxVal),
Random.Range(minVal, maxVal),
Random.Range(minVal, maxVal));
else
Debug.LogError("Select a GameObject to randomize its position.");
}
复制代码

 

效果:   
 
9.Popup弹出选择菜单
Popup(int selectedIndex,string[] displayOptions,GUILayoutOption[] paroptions)                           Popup(int selectedIndex,string[] displayOptions,GUIStyle style,GUILayoutOption[] paroptions)
Popup(string label,int selectedIndex,string[] displayOptions,GUILayoutOption[] paroptions)          Popup(GUIContent label,int selectedIndex,string[] displayOptions,GUILayoutOption[] paroptions)。。。。
//参数:label字段前面可选标签  selectedIndex字段选项的索引  displayedOptions弹出菜单选项的数组  style可选样式 options。。
//返回:int,用户选择的选项索引
复制代码
string[] options ={"Cube","Sphere","Plane"};
int index =0;
voidOnGUI()
{
index =EditorGUILayout.Popup(index, options);
if(GUILayout.Button("Create"))
InstantiatePrimitive();
}
voidInstantiatePrimitive(){
switch(index){
case0:
GameObject cube=GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position =Vector3.zero;
break;
case1:
GameObject sphere=GameObject.CreatePrimitive(PrimitiveType.Sphere);
sphere.transform.position =Vector3.zero;
break;
case2:
GameObject plane=GameObject.CreatePrimitive(PrimitiveType.Plane);
plane.transform.position =Vector3.zero;
break;
default:
Debug.LogError("Unrecognized Option");
break;
}
}
}
复制代码

 

效果:
 
10.EnumPopup 枚举弹出选择菜单(效果同上)
//返回System.Enum,用户选择的枚举选项。
复制代码
enum OPTIONS
{
CUBE =0,
SPHERE =1,
PLANE =2
}
publicclass myEditor3 :EditorWindow{
OPTIONS op=OPTIONS.CUBE;
[MenuItem("cayman/tempShow")]
staticvoid newWelcome()
{
myEditor3 window3 =(myEditor3)EditorWindow.GetWindow(typeof(myEditor3),true,"Eam");
window3.Show();
}
voidOnGUI()
{
op =(OPTIONS)EditorGUILayout.EnumPopup("Primitive to create:", op);
}
}
复制代码

 

 
11.IntPopup 整数弹出选择菜单
IntPopup(string label,int selectedValue,string[] displayOptions,int[] optionValues,GUIStyle style,GUILayoutOption[] paramsOptions).....
//参数:label字段前面的可选标签  selectedValue字段选项的索引 displayOptions弹出菜单項数组 optionValues每个选项带有值的数组。。
//返回:int,用户选择的选项的值
复制代码
int selectedSize =1;
string[] names ={"Normal","Double","Quadruple"};
int[] sizes ={1,2,4};
voidOnGUI()
{
selectedSize =EditorGUILayout.IntPopup("Resize Scale: ", selectedSize, names, sizes);
if(GUILayout.Button("Scale"))
ReScale();
}
voidReScale()
{
if(Selection.activeTransform)
Selection.activeTransform.localScale =newVector3(selectedSize, selectedSize, selectedSize);
elseDebug.LogError("No Object selected, please select an object to scale.");
}
复制代码

 

效果:
 
12.TagField 标签字段   LayerField层字段
1/ TagField(string label,string tag,GUIStyle style,GUILayoutOption[] paramsOptions)...
//参数:label字段前面的可选标签  tag显示字段的标签 。。
//返回:string,用户选择的标签
2/ LayerField(string label,int layer,GUIStyle style,GUILayoutOption[] paramsOptions)...
参数:label字段前面的可选标签 layer显示在该字段的层。。
//返回:int,用户选择的层
复制代码
string tagStr ="";
    int selectedLayer=0;
voidOnGUI()
{ //为游戏物体设置
tagStr =EditorGUILayout.TagField("Tag for Objects:", tagStr);
if(GUILayout.Button("Set Tag!"))
SetTags();
if(GUILayout.Button("Set Layer!"))
            SetLayer();
}
voidSetTags(){
foreach(GameObject go inSelection.gameObjects)
go.tag = tagStr;
}
    voidSetLayer(){
foreach(GameObject go inSelection.gameObjects)
go.laye= tagStr;
}
复制代码

 

效果:
 
13.ObjectField 物体字段(拖拽物体或拾取器选择物体)
ObjectField(string label,Object obj,Type objType,bool allowSceneObjects,GUILayoutOption[] paramsOptions)
//label字段前面的可选标签   obj字段显示的物体   objType物体的类型    allowSceneObjects允许指定场景物体..
//返回:Object,用户设置的物体
复制代码
Object source;
Texture myme;
voidOnGUI()
{
EditorGUILayout.BeginHorizontal();
source =EditorGUILayout.ObjectField("hiahia",source,typeof(Object));
myme= (Texture)EditorGUILayout.ObjectField("hehe",myme,typeof(Texture));//注意类型转换
EditorGUILayout.EndHorizontal();
}
复制代码
效果:
 
14.Vector2Field 二维向量字段   Vector3Field 三维向量字段(略,同2维)
Vector2Field (string label,Vector2 value,GUILayoutOption[] options)
//参数:label字段前面的可选标签  value编辑的值  options...
//返回:Vector2,由用户输入的值
复制代码
float distance =0;
Vector2 p1, p2;
voidOnGUI()
{
p1 =EditorGUILayout.Vector2Field("Point 1:", p1);
p2 =EditorGUILayout.Vector2Field("Point 2:", p2);
EditorGUILayout.LabelField("Distance:", distance.ToString());
}
voidOnInspectorUpdate()//面板刷新
{
distance =Vector2.Distance(p1, p2);
this.Repaint();
}
复制代码

 

效果:
 
15.ColorField 颜色字段
ColorField (string label,Color value,...)
//参数:label字段前面的可选标签  value编辑的值
//返回:Color,由用户输入的值
复制代码
Color matColor =Color.white;
voidOnGUI()
{
matColor =EditorGUILayout.ColorField("New Color", matColor);
if(GUILayout.Button("Change!"))
ChangeColors();
}
voidChangeColors(){
if(Selection.activeGameObject)
foreach(var t inSelection.gameObjects)
if(t.GetComponent<Renderer>())
t.GetComponent<Renderer>().sharedMaterial.color = matColor;
}
复制代码

 

效果:
 
16.
EditorWindow.GetWindowWithRect() 和 EditorWindow.GetWindow()都可以创建一个窗口。前者可以规定窗口的区域,后者可通过鼠标动态的延伸窗口。参数1表示窗口的对象,参数2表示窗口的区域,参数3表示窗口类型true表示窗口不会被别的窗口覆盖,参数4表示窗口的名称。
  1. using UnityEngine;
  2. using UnityEditor;
  3. publicclassMyEditor:EditorWindow
  4. {
  5. [MenuItem("GameObject/caymanwindow")]
  6. staticvoidAddWindow()
  7. {
  8. //创建窗口
  9. Rect wr =newRect(0,0,500,500);
  10. MyEditor window =(MyEditor)EditorWindow.GetWindowWithRect(typeof(MyEditor),wr,true,"widown name");
  11. window.Show();
  12. }
  13. //输入文字的内容
  14. privatestring text;
  15. //选择贴图的对象
  16. privateTexture texture;
  17. float myFloat =1.23f;
  18. private bool kaiguan;//开关
  19. private bool groupEnabled;//区域开关
  20. publicvoidAwake()
  21. {
  22. //在资源中读取一张贴图
  23. texture =Resources.Load("1")asTexture;
  24. }
  25. //绘制窗口时调用
  26. voidOnGUI()
  27. {
  28. //输入框控件
  29. text =EditorGUILayout.TextField("输入文字:",text);//3.制作一个文本字段
  30. if(GUILayout.Button("打开通知",GUILayout.Width(200)))
  31. {
  32. //打开一个通知栏
  33. this.ShowNotification(newGUIContent("This is a Notification"));
  34. }
  35. if(GUILayout.Button("关闭通知",GUILayout.Width(200)))
  36. {
  37. //关闭通知栏
  38. this.RemoveNotification();
  39. }
  40. //文本框显示鼠标在窗口的位置
  41. EditorGUILayout.LabelField("鼠标在窗口的位置",Event.current.mousePosition.ToString());//1.制作一个标签字段(通常用于显示只读信息)
  42. showBtn = EditorGUILayout.Toggle("开关", showBtn);
     
            groupEnabled = EditorGUILayout.BeginToggleGroup("Optional Settings", groupEnabled);
            text21 = EditorGUILayout.TextField("请输入帐号:", text21);
            text3 = EditorGUILayout.PasswordField("请输入密码",text3); //密码输入
            if (GUILayout.Button("登录", GUILayout.Width(400)))
            {
                //
            }
            int01 = EditorGUILayout.IntField("输入实例化份数:",int01);
            if (GUILayout.Button("实例化"))   //根据份数,实例化选择的物体
            {
                for (int i = 0; i < int01; i++)
                {
                    Instantiate(Selection.activeGameObject,Vector3.zero,Quaternion.identity);
                }
            }
     
            EditorGUILayout.EndToggleGroup();
            scale1 = EditorGUILayout.Slider(scale1,1,100); //滑动条
            index = EditorGUILayout.Popup(index,options); //弹出选择菜单
            if(GUILayout.Button("创建一个")){
                switch (index)
                {
                    case 0:
                        GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
                        cube.transform.position = Vector3.zero;
                        break;
                    case 1:
                        GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
                        sphere.transform.position = Vector3.zero;
                        break;
                    case 2:
                        GameObject plane = GameObject.CreatePrimitive(PrimitiveType.Plane);
                        plane.transform.position = Vector3.zero;
                        break;
                    default:
                        break;
                }
            }
     
            showPosition = EditorGUILayout.Foldout(showPosition, status);     //制作一个左侧带有箭头的折叠标签
            if (showPosition)
            {
                if (Selection.activeTransform)
                {
                    Selection.activeTransform.position =
                        EditorGUILayout.Vector3Field("Position", Selection.activeTransform.position);
                    status = Selection.activeTransform.name;
                }
     
                if (!Selection.activeTransform)
                {
                    status = "Select a GameObject";
                    showPosition = false;
                }
            }
  43. //选择贴图
  44. texture =EditorGUILayout.ObjectField("添加贴图",texture,typeof(Texture),true)asTexture;
  45. groupEnabled =EditorGUILayout.BeginToggleGroup("Optional Settings",groupEnabled);//起始----------------------------
  46. //这里放开关区域内内容
  47. myFloat =EditorGUILayout.Slider("Slider", myFloat,-3,3);//滑动条
  48. kaiguan=EditorGUILayout.Toggle("开关", kaiguan);//2.开关
  49. EditorGUILayout.EndToggleGroup();//结束-------------------------------------
  50. if(GUILayout.Button("关闭窗口",GUILayout.Width(200)))
  51. {
  52. //关闭窗口
  53. this.Close();
  54. }
  55. }
  56. voidOnFocus()
  57. {
  58. Debug.Log("当窗口获得焦点时调用一次");
  59. }
  60. voidOnLostFocus()
  61. {
  62. Debug.Log("当窗口丢失焦点时调用一次");
  63. }
  64. voidOnHierarchyChange()
  65. {
  66. Debug.Log("当Hierarchy视图中的任何对象发生改变时调用一次");
  67. }
  68. voidOnProjectChange()
  69. {
  70. Debug.Log("当Project视图中的资源发生改变时调用一次");
  71. }
  72. voidOnInspectorUpdate()//实时刷新面板
  73. {
  74. //Debug.Log("窗口面板的更新");
  75. //这里开启窗口的重绘,不然窗口信息不会刷新
  76. this.Repaint();
  77. }
  78. voidOnSelectionChange()
  79. {
  80. //当窗口出去开启状态,并且在Hierarchy视图中选择某游戏对象时调用
  81. foreach(Transform t inSelection.transforms)
  82. {
  83. //有可能是多选,这里开启一个循环打印选中游戏对象的名称
  84. Debug.Log("OnSelectionChange"+ t.name);
  85. }
  86. }
  87. voidOnDestroy()
  88. {
  89. Debug.Log("当窗口关闭时调用");
  90. }
  91. }
  92. //http://www.ceeger.com/Script/EditorGUILayout/EditorGUILayout.html
 
然后我们在扩充一下自定义窗口,仔细看看窗口的生命周期。
  1.  
 
 
 
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Unity编辑器拓展Editor Extension)可以通过自定义的脚本来扩展Unity编辑器的功能和界面,以满足特定项目的需求。通过编辑器拓展,开发者可以创建自定义编辑器窗口、工具栏按钮、菜单项、检视面板等,来增强Unity编辑器的功能和流程。 要创建一个Unity编辑器拓展,你可以使用C#编写一个继承自Editor的脚本。这个脚本可以通过Unity的Inspector面板来设置相关的属性和行为。以下是一个简单的示例: ```csharp using UnityEngine; using UnityEditor; public class MyEditorExtension : EditorWindow { [MenuItem("Custom Tools/My Editor Window")] public static void OpenWindow() { // 创建并打开一个自定义编辑器窗口 MyEditorExtension window = (MyEditorExtension)EditorWindow.GetWindow(typeof(MyEditorExtension)); window.Show(); } private void OnGUI() { // 在编辑器窗口绘制UI元素 GUILayout.Label("Hello, I am a custom editor window!"); if (GUILayout.Button("Click Me")) { Debug.Log("Button clicked!"); } } } ``` 上述代码创建了一个自定义编辑器窗口,并在窗口绘制了一个标签和一个按钮。通过在Unity编辑器点击"Custom Tools"菜单下的"My Editor Window",可以打开这个自定义编辑器窗口。 除了编辑器窗口,你还可以通过继承Editor来创建自定义的检视面板、菜单项等。Unity官方文档有更详细的教程和示例,可以帮助你更深入地了解和使用Unity编辑器拓展

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值