天天看點

拓展自定義編輯器視窗(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();

//實時重新整理

}

}

  

效果:

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

  2.Toggle開關按鈕 Toggle(bool value,GUILayoutOption[] options) Toggle(string label,bool value,GUILayoutOption[] options) //參數:label開關按鈕前面的可選标簽  value開關按鈕的顯示狀态 options額外布局屬性的可選清單   //傳回:bool,開關按鈕的選擇狀态

拓展自定義編輯器視窗(EditorGUILayout類)
//如果開關控件被選擇,顯示一個按鈕。
bool showBtn =true;
voidOnGUI()
{
showBtn =EditorGUILayout.Toggle("Show Button", showBtn);
if(showBtn)
{
if(GUILayout.Button("Close"))
this.Close();
}
}      
拓展自定義編輯器視窗(EditorGUILayout類)

效果:

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

  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,使用者輸入的文本

拓展自定義編輯器視窗(EditorGUILayout類)
//通過字段,自動改變選擇物體的名字
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();//實時重新整理
}
}      
拓展自定義編輯器視窗(EditorGUILayout類)

效果:

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

  4.TextArea文本區域 TextArea(string text,GUILayoutOption[] options) TextArea(string text,GUIStyle style,GUILayoutOption[] options) //參數:text可編輯的文本  style可選樣式 options額外布局屬性的可選清單 //傳回:string,使用者輸入的文本

拓展自定義編輯器視窗(EditorGUILayout類)
//在編輯器視窗可視化腳本,這可擴充儲存腳本
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;
}
}      
拓展自定義編輯器視窗(EditorGUILayout類)

效果:

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

  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,使用者輸入的密碼  

拓展自定義編輯器視窗(EditorGUILayout類)
//建立密碼字段并可視化在密碼字段有什麼鍵入。
string text ="Some text here";
function OnGUI(){
text =EditorGUILayout.PasswordField("Type Something:",text);
EditorGUILayout.LabelField("Written Text:", text);
}
}      
拓展自定義編輯器視窗(EditorGUILayout類)

效果:

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

  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);

}

}

  

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

  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);

}

  

拓展自定義編輯器視窗(EditorGUILayout類)
//随機放置選擇的物體在最小最大滑動條之間
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.");
}      
拓展自定義編輯器視窗(EditorGUILayout類)

效果:

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

  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,使用者選擇的選項索引

拓展自定義編輯器視窗(EditorGUILayout類)
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;
}
}
}      
拓展自定義編輯器視窗(EditorGUILayout類)

效果:

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

  10.EnumPopup 枚舉彈出選擇菜單(效果同上) //傳回System.Enum,使用者選擇的枚舉選項。

拓展自定義編輯器視窗(EditorGUILayout類)
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);
}
}      
拓展自定義編輯器視窗(EditorGUILayout類)

  11.IntPopup 整數彈出選擇菜單 IntPopup(string label,int selectedValue,string[] displayOptions,int[] optionValues,GUIStyle style,GUILayoutOption[] paramsOptions)..... //參數:label字段前面的可選标簽  selectedValue字段選項的索引 displayOptions彈出菜單項數組 optionValues每個選項帶有值的數組。。 //傳回:int,使用者選擇的選項的值

拓展自定義編輯器視窗(EditorGUILayout類)
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.");
}      
拓展自定義編輯器視窗(EditorGUILayout類)

效果:

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

  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,使用者選擇的層

拓展自定義編輯器視窗(EditorGUILayout類)
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;
}      
拓展自定義編輯器視窗(EditorGUILayout類)

效果:

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

  13.ObjectField 物體字段(拖拽物體或拾取器選擇物體) ObjectField(string label,Object obj,Type objType,bool allowSceneObjects,GUILayoutOption[] paramsOptions) //label字段前面的可選标簽   obj字段顯示的物體   objType物體的類型    allowSceneObjects允許指定場景物體.. //傳回:Object,使用者設定的物體

拓展自定義編輯器視窗(EditorGUILayout類)
Object source;
Texture myme;
voidOnGUI()
{
EditorGUILayout.BeginHorizontal();
source =EditorGUILayout.ObjectField("hiahia",source,typeof(Object));
myme= (Texture)EditorGUILayout.ObjectField("hehe",myme,typeof(Texture));//注意類型轉換
EditorGUILayout.EndHorizontal();
}      
拓展自定義編輯器視窗(EditorGUILayout類)

效果:

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

  14.Vector2Field 二維向量字段   Vector3Field 三維向量字段(略,同2維) Vector2Field (string label,Vector2 value,GUILayoutOption[] options) //參數:label字段前面的可選标簽  value編輯的值  options... //傳回:Vector2,由使用者輸入的值

拓展自定義編輯器視窗(EditorGUILayout類)
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();
}      
拓展自定義編輯器視窗(EditorGUILayout類)

效果:

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

  15.ColorField 顔色字段 ColorField (string label,Color value,...)

//參數:label字段前面的可選标簽  value編輯的值 //傳回:Color,由使用者輸入的值

拓展自定義編輯器視窗(EditorGUILayout類)
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;
}      
拓展自定義編輯器視窗(EditorGUILayout類)

效果:

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

  16. EditorWindow.GetWindowWithRect() 和 EditorWindow.GetWindow()都可以建立一個視窗。前者可以規定視窗的區域,後者可通過滑鼠動态的延伸視窗。參數1表示視窗的對象,參數2表示視窗的區域,參數3表示視窗類型true表示視窗不會被别的視窗覆寫,參數4表示視窗的名稱。

拓展自定義編輯器視窗(EditorGUILayout類)
  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

  然後我們在擴充一下自定義視窗,仔細看看視窗的生命周期。

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

繼續閱讀