1. 程式人生 > >Unity Editor 基礎篇(九):EditorUtility編輯器工具

Unity Editor 基礎篇(九):EditorUtility編輯器工具

EditorUtility 編輯器工具

轉自:http://blog.csdn.net/liqiangeastsun/article/details/42174339,請檢視原文,尊重樓主原創版權。

這是一個編輯器類,如果想使用它你需要把它放到工程目錄下的Assets/Editor資料夾下。

編輯器類在UnityEditor名稱空間下。所以當使用C#指令碼時,你需要在指令碼前面加上 "using UnityEditor"引用。

1.ProgressBar 進度條

在Editor資料夾中新增指令碼:

using UnityEngine;  
using System.Collections;  
using UnityEditor;  
  
public class TestEditor : EditorWindow  
{  
    float secs = 10.0f;  
    double startVal = 0;  
    double progress = 0;  
    bool isShow = false;  
  
    [MenuItem("Examples/Cancelable Progress Bar Usage")]   
    static void Init()  
    {  
        var window = GetWindow(typeof(TestEditor));  
        window.Show();  
    }  
  
    void OnGUI()  
    {  
        secs = EditorGUILayout.FloatField("Time to wait:", secs);  
        if (GUILayout.Button("Display bar"))  
        {  
            startVal = EditorApplication.timeSinceStartup; //開始編譯到現在的時間  
            isShow = !isShow;  
        }  
  
        if (GUILayout.Button("Clear bar"))  
        {  
            EditorUtility.ClearProgressBar(); //清空進度條的值, 基本沒什麼用  
        }  
  
        if (progress < secs && isShow == true)  
        {     
            //使用這句程式碼,在進度條後邊會有一個 關閉按鈕,但是用這句話會直接卡死,切記不要用  
           // EditorUtility.DisplayCancelableProgressBar("Simple Progress Bar", "Show a progress bar for the given seconds", (float)(progress / secs));  
            //使用這句建立一個進度條,  引數1 為標題,引數2為提示,引數3為 進度百分比 0~1 之間  
            EditorUtility.DisplayProgressBar("Simple Progress Bar", "Show a progress bar for the given seconds", (float)(progress / secs));  
        }  
        else {  
            startVal = EditorApplication.timeSinceStartup;  
            progress = 0.0f;  
            return;  
        }  
            progress = EditorApplication.timeSinceStartup - startVal;  
    }  
  
    void OnInspectorUpdate() //更新  
    {  
        Repaint();  //重新繪製  
    }  
}  

效果:

2.CollectDeepHierarchy收集深度層級

遍歷物件以及子物體,以及子物體上繫結的所有元件

using UnityEngine;  
using System.Collections;  
using UnityEditor;  
  
public class Test : MonoBehaviour { //遍歷物件以及子物體,以及子物體上繫結的所有元件  
  
    private GameObject parent;   
  
    // Use this for initialization  
    void Start () {  
        Init();  
    }  
  
    void Init()  
    {  
        parent = gameObject;  // 給parent賦值 為 gameObject ,在Hierarchy 中給該物件建立幾個子物體  
        Object[] obj = new Object[1];  
        obj[0] = parent; //將parent新增至 陣列  
        Object[] result = EditorUtility.CollectDeepHierarchy(obj);  
  
        foreach (Object ob in result) //遍歷 所有物件,得到物件本身包括子物件上繫結的所有元件  
        {  
            print(ob + "        " + ob.name); //  
        }  
    }  
}  

3.CompressTexture壓縮一個紋理到指定的格式

using UnityEngine;  
using System.Collections;  
using UnityEditor;  
  
public class Test : AssetPostprocessor { //   
  
    void OnPostprocessTexture(Texture2D T) //使用該方法壓縮一個紋理到指定的格式  
    {  
        //該方法需使用 Texture2D, 使用該方法比較快速但是會降低效果  
        EditorUtility.CompressTexture(T, TextureFormat.RGB24, TextureCompressionQuality.Best);  
    }  
}  

4.CreateGameObjectWithHideFlags 建立帶有標識的遊戲物體

在Editor資料夾下建立指令碼:

using UnityEngine;  
using System.Collections;  
using UnityEditor;  
  
public class TestEditor : EditorWindow  
{  
    private string objName = "GameObject";  
    private int instanceID = 0;  
    private bool create = true;  
    private GameObject go = null;  
  
    private bool hideHierarchy = true;  
  
    [MenuItem("Examples/GameObject flags")]  
    static void Init()  
    {  
        TestEditor window = (TestEditor)GetWindow(typeof(TestEditor)); //初始化一個視窗  
        window.Show();  
    }  
  
    void OnGUI()  
    {  
        create = EditorGUILayout.Toggle("Create a GO:", create); //在視窗建立一個 Toggle  
  
        GUI.enabled = create;  //GUI是否可以建立  
        objName = EditorGUILayout.TextField("GameObject Name:", objName); //建立文字框  
        if (GUILayout.Button("Create"))  //建立按鈕  
        {  //點選按鈕,建立一個GameObject  
            GameObject created = EditorUtility.CreateGameObjectWithHideFlags(  
                    objName,  
                    hideHierarchy ? HideFlags.HideInHierarchy : 0);  
            //HideFlags.HideInHierarchy  物件在Hierarchy 視窗隱藏  
            //HideFlags.HideInInspector  物件在Hierarchy視窗可見,點選該物件,在Inspector面板不顯示任何屬性  
            GameObject ccc = EditorUtility.CreateGameObjectWithHideFlags("cccc", HideFlags.HideInInspector);  
            Debug.Log("Created GameObject ID: " + created.GetInstanceID());  
        }  
  
        GUI.enabled = !create;   
        EditorGUILayout.BeginHorizontal(); //開始水平佈局  
        instanceID = EditorGUILayout.IntField("Instance ID:", instanceID); //建立一個 整數輸入框  
        if (GUILayout.Button("Search & Update flags"))  //建立一個按鈕,更新flags  
        {  
            go = null;  
            go = (GameObject)EditorUtility.InstanceIDToObject(instanceID); //給該物件例項化一個ID  
            if (go)  
                go.hideFlags = hideHierarchy ? HideFlags.HideInHierarchy : 0;  
        }  
        EditorGUILayout.EndHorizontal(); //結束水平佈局  
  
        if (!go)  
            EditorGUILayout.LabelField("Object: ", "No object was found");  
        else  
            EditorGUILayout.LabelField("Object: ", go.name);  
  
        GUI.enabled = true;  
        hideHierarchy = EditorGUILayout.Toggle("HideInHierarchy", hideHierarchy); //建立一個Toggle ,  
  
    }  
}  

效果:

Unity在選單欄建立按鈕,點選按鈕建立一個視窗,在視窗上建立 Toggle、TextField、button等, 在視窗建立了一個Create按鈕,點選按鈕建立物件

勾選 Create a Go: 的Toggle,顯示Create按鈕 點選Create按鈕,在 Hierarchy 視窗建立 物件“aaa” “ccc”

選中 “aaa”,Inspector視窗如下所示

選中 “cccc” 在,Inspector視窗如下所示,”cccc“繫結的元件在Inspector面板隱藏

5.DisplayDialog顯示對話方塊  DisplayDialogComplex 顯示覆雜對話方塊

用於在編輯器顯示訊息框。

1.DisplayDialog顯示對話方塊(返回true/false)

ok 和 cancel 是顯示在對話方塊按鈕上的標籤,如果cancel為空(預設),然只有一個按鈕被顯示。如果ok按鈕被按下,DisplayDialog返回true。

//在地形的表面上放置選擇的物體。
using UnityEngine;
using UnityEditor;
 
public class PlaceSelectionOnSurface : ScriptableObject {
	[MenuItem ("Example/Place Selection On Surface")]
	static void CreateWizard () {
		Transform[] transforms = Selection.GetTransforms(SelectionMode.Deep |
		SelectionMode.ExcludePrefab | SelectionMode.OnlyUserModifiable);
 
		if (transforms.Length > 0 &&
			EditorUtility.DisplayDialog("Place Selection On Surface?",
			"Are you sure you want to place " + transforms.Length
			+ " on the surface?", "Place", "Do Not Place")) {
			foreach (Transform transform in transforms) {
				RaycastHit hit;
				if (Physics.Raycast(transform.position, Vector3.down, out hit)) {
					transform.position = hit.point;
					Vector3 randomized = Random.onUnitSphere;
					randomized = new Vector3(randomized.x, 0F, randomized.z);
					transform.rotation = Quaternion.LookRotation(randomized, hit.normal);
				}
			}
		}
	}
}

2. DisplayDialogComplex 顯示覆雜對話方塊(返回0/1/2對應ok/cancel/alt)

//讓你儲存,儲存並退出或退出不儲存
class EditorUtilityDisplayDialogComplex extends MonoBehaviour {
 
	@MenuItem("Examples/Enhanced Save")
	static function Init() {
		var option = EditorUtility.DisplayDialogComplex(
			"What do you want to do?",
			"Please choose one of the following options.",
			"Save Scene",
			"Save and Quit",
			"Quit without saving");
		switch (option) {
			// Save Scene //儲存場景
			case 0:
			EditorApplication.SaveScene(EditorApplication.currentScene);
			break;
			// Save and Quit. //儲存並退出
			case 1:
			EditorApplication.SaveScene(EditorApplication.currentScene);
			EditorApplication.Exit(0);
			break;
			// Quit Without saving. // 退出不儲存
			case 2:
			EditorApplication.Exit(0);
			break;
			default:
			Debug.LogError("Unrecognized option.");
 
		}
	}
}

6.DisplayPopupMenu顯示彈出選單

static function DisplayPopupMenu (position : Rect, menuItemPath : string, command : MenuCommand) : void

選單顯示在position位置,從menuItemPath指定的子選單生成,使用MenuCommand作為選單上下文。

在Editor資料夾下建立指令碼TestEditor   
using UnityEngine;  
using System.Collections;  
using UnityEditor;  
  
public class TestEditor : EditorWindow    
{  
    [MenuItem("Examples/Enhanced Save")]  
    static void Init()  
    {  
  
        Rect contextRect = new Rect(10, 10, 100, 100);  
        EditorUtility.DisplayPopupMenu(contextRect, "Assets/", null);  
    }  
}  

在工具欄建立Button點選Button,在Asset下建立視窗

雙擊“Enbanced Save”顯示如下視窗,即Asset下建立視窗

7.FocusProjectWindow焦點專案視窗

使專案視窗到前面並焦點它,這個通常在一個選單項建立並選擇一個資源之後被呼叫。

8.SaveFilePanel儲存檔案面板

Unity編輯器之匯入匯出獲取路徑對話方塊:

選中一個圖片,點選 “Save Texture to file”按鈕:

在Editor資料夾下建立指令碼  
using UnityEngine;  
using System.Collections;  
using UnityEditor;  
using System.IO;  
  
public class TestEditor : EditorWindow  
{  
    [MenuItem("Examples/Save Texture to file")]  
    static void Apply()  
    {  
  
        Texture2D texture = Selection.activeObject as Texture2D; //選中一個圖片  
        if (texture == null)  
        {  //如果沒選圖片,顯示提示對話方塊  
            EditorUtility.DisplayDialog(  
                "Select Texture",  
                "You Must Select a Texture first!",  
                "Ok");  
            return;  
        }  
        //獲取路徑  
        string path = EditorUtility.SaveFilePanel(  
                "Save texture as PNG",  
                "",  
                texture.name + ".png",  
                "png");  
  
        if (path.Length != 0)  
        {  
            // Convert the texture to a format compatible with EncodeToPNG  
            if (texture.format != TextureFormat.ARGB32 && texture.format != TextureFormat.RGB24)  
            {  
                Texture2D newTexture = new Texture2D(texture.width, texture.height);  
                newTexture.SetPixels(texture.GetPixels(0), 0);  
                texture = newTexture;  
            }  
            var pngData = texture.EncodeToPNG();  
            if (pngData != null)  
                File.WriteAllBytes(path, pngData);  
        }  
    }  
}