拓展自定義編輯器窗口(EditorGUILayout類)

Unity支持自行建立窗口,也支持自定義窗口布局。在Project視圖中建立一個Editor文件夾,在文件夾中再建立一條腳本。html

自定義窗口須要讓腳本繼承EditorWindow再設置MenuItem,此時在Unity導航菜單欄中GameObjec->window就可建立一個自定義窗口。數組

0.窗口:dom

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額外佈局屬性可選列表  --無返回值
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    整數字段返回整數,由用戶輸入的值
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-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.  
 
 
 
 
 
 
 
 
 
 
 
 
 
 



相關文章
相關標籤/搜索