Unity编辑器扩展学习

https://www.xuanyusong.com/archives/category/unity/unity3deditor

 

1

Unity编辑器扩展学习 _第1张图片

using UnityEngine;

public class Test : MonoBehaviour {
    public Rect rect;
    public Texture texture;
}


using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(Test))]
public class MyEditor: Editor {
    public override void OnInspectorGUI() {
        Test test = (Test)target;
        test.rect = EditorGUILayout.RectField("窗口坐标", test.rect);
        test.texture = EditorGUILayout.ObjectField("增加一个贴图", test.texture, typeof(Texture), true) as Texture;
    }
}
View Code

2

Unity编辑器扩展学习 _第2张图片

using UnityEngine;
using UnityEditor;

public class MyEditor: EditorWindow {

    private string text;
    private Texture texture;

    [MenuItem("GameObject/window")]
    public static void AddWindow() {
        Rect rect = new Rect(0, 0, 500, 500);
        MyEditor window = (MyEditor)EditorWindow.GetWindowWithRect(typeof(MyEditor), rect, true, "window one");
        window.Show();
    }

    public void OnGUI() {
        text = EditorGUILayout.TextField("输入文字:", text);

        if (GUILayout.Button("打开通知", GUILayout.Width(200))) {
            ShowNotification(new GUIContent("This is a Notification"));
        }

        if (GUILayout.Button("关闭通知", GUILayout.Width(200))) {
            this.RemoveNotification();
        }

        EditorGUILayout.LabelField("鼠标在窗口的位置", Event.current.mousePosition.ToString());

        texture = EditorGUILayout.ObjectField("添加贴图", texture, typeof(Texture), true) as Texture;

        if (GUILayout.Button("关闭窗口", GUILayout.Width(200))) {
            Close();
        }
    }


    public void OnFocus() {
        Debug.Log("当窗口获得焦点时调用一次");
    }

    public void OnLostFocus() {
        Debug.Log("当窗口丢失焦点时调用一次");
    }

    public void OnHierarchyChange() {
        Debug.Log("当Hierarchy视图中的任何对象发生改变时调用一次");
    }

    public void OnProjectChange() {
        Debug.Log("当Project视图中的资源发生改变时调用一次");
    }

    public void OnInspectorUpdate() {
        // Debug.Log("窗口面板的更新");
        // 这里开启窗口的重绘,不然窗口信息不会刷新
        this.Repaint();
    }

    public void OnSelectionChange() {
        foreach (Transform t in Selection.transforms) {
            Debug.Log("OnSelectionChange: " + t.name);
        }
    }

    public void OnDestroy() {
        Debug.Log("当窗口关闭时调用");
    }
}
View Code

3

Unity编辑器扩展学习 _第3张图片

using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(Test))]
public class MyEditor: Editor {

    public void OnSceneGUI() {
        Test test = (Test)target;

        Handles.Label(test.transform.position + Vector3.up * 2, test.transform.name + " : " + test.transform.position.ToString());
        Handles.BeginGUI();

        GUILayout.BeginArea(new Rect(100, 100, 100, 100));

        if (GUILayout.Button("这是一个按钮!")) {
            Debug.Log("test");
        }

        GUILayout.Label("我在编辑Scene视图");

        GUILayout.EndArea();

        Handles.EndGUI();
    }
}
View Code
using UnityEngine;
using UnityEditor;

public class MyEditor: Editor {

    [DrawGizmo(GizmoType.InSelectionHierarchy | GizmoType.NotInSelectionHierarchy)]
    public static void DrawGameObjectName(Transform transform, GizmoType gizmoType) {
        Handles.Label(transform.position, transform.gameObject.name);
    }
}
View Code

4

Unity编辑器扩展学习 _第4张图片

using UnityEngine;
using UnityEditor;

public class MyEditor: Editor {

    [MenuItem("MyMenu/Do Test")]
    public static void Test() {
        Transform parent = Selection.activeGameObject.transform;
        Vector3 postion = parent.position;
        Quaternion rotation = parent.rotation;
        Vector3 scale = parent.localScale;
        parent.position = Vector3.zero;
        parent.rotation = Quaternion.Euler(Vector3.zero);
        parent.localScale = Vector3.one;

        Collider[] colliders = parent.GetComponentsInChildren();
        foreach (Collider child in colliders) {
            DestroyImmediate(child);
        }
        Vector3 center = Vector3.zero;
        Renderer[] renders = parent.GetComponentsInChildren();
        foreach (Renderer child in renders) {
            center += child.bounds.center;
        }
        center /= parent.transform.childCount;
        Bounds bounds = new Bounds(center, Vector3.zero);
        foreach (Renderer child in renders) {
            bounds.Encapsulate(child.bounds);
        }
        BoxCollider boxCollider = parent.gameObject.AddComponent();
        boxCollider.center = bounds.center - parent.position;
        boxCollider.size = bounds.size;

        parent.position = postion;
        parent.rotation = rotation;
        parent.localScale = scale;
    }

}
View Code

5

Unity编辑器扩展学习 _第5张图片

using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections.Generic;

[CustomEditor(typeof(UnityEditor.DefaultAsset))]
public class FolderInspector : Editor {

    Data data;
    Data selectData;

    void OnEnable() {
        if (Directory.Exists(AssetDatabase.GetAssetPath(target))) {
            data = new Data();
            LoadFiles(data, AssetDatabase.GetAssetPath(Selection.activeObject));
        }

    }
    public override void OnInspectorGUI() {

        if (Directory.Exists(AssetDatabase.GetAssetPath(target))) {
            GUI.enabled = true;
            EditorGUIUtility.SetIconSize(Vector2.one * 16);
            DrawData(data);
        }

    }

    void LoadFiles(Data data, string currentPath, int indent = 0) {
        GUIContent content = GetGUIContent(currentPath);

        if (content != null) {
            data.indent = indent;
            data.content = content;
            data.assetPath = currentPath;

        }

        foreach (var path in Directory.GetFiles(currentPath)) {
            content = GetGUIContent(path);
            if (content != null) {
                Data child = new Data();
                child.indent = indent + 1;
                child.content = content;
                child.assetPath = path;
                data.childs.Add(child);
            }
        }


        foreach (var path in Directory.GetDirectories(currentPath)) {
            Data childDir = new Data();
            data.childs.Add(childDir);
            LoadFiles(childDir, path, indent + 1);
        }
    }



    void DrawData(Data data) {
        if (data.content != null) {
            EditorGUI.indentLevel = data.indent;
            DrawGUIData(data);

        }
        for (int i = 0; i < data.childs.Count; i++) {
            Data child = data.childs[i];
            if (child.content != null) {
                EditorGUI.indentLevel = child.indent;
                if (child.childs.Count > 0)
                    DrawData(child);
                else
                    DrawGUIData(child);
            }
        }
    }


    void DrawGUIData(Data data) {
        GUIStyle style = "Label";
        Rect rt = GUILayoutUtility.GetRect(data.content, style);
        if (data.isSelected) {
            EditorGUI.DrawRect(rt, Color.gray);
        }

        rt.x += (16 * EditorGUI.indentLevel);
        if (GUI.Button(rt, data.content, style)) {
            if (selectData != null) {
                selectData.isSelected = false;
            }
            data.isSelected = true;
            selectData = data;
            Debug.Log(data.assetPath);
        }
    }

    GUIContent GetGUIContent(string path) {
        Object asset = AssetDatabase.LoadAssetAtPath(path, typeof(Object));
        if (asset) {
            return new GUIContent(asset.name, AssetDatabase.GetCachedIcon(path));
        }
        return null;
    }

    class Data {
        public bool isSelected = false;
        public int indent = 0;
        public GUIContent content;
        public string assetPath;
        public List childs = new List();
    }
}
View Code

6

using UnityEngine;
using UnityEditor;
using System.Collections;
using System;

public class MyEditor {

    [InitializeOnLoadMethod]
    static void Start() {
        Action OnEvent = delegate {
            Event e = Event.current;

            switch (e.type) {
                //            case EventType.mouseDown:                
                //                Debug.Log ("mousedown");
                //                e.Use ();
                //                break;
                //            case EventType.mouseUp:            
                //                Debug.Log ("mouseup");
                //                e.Use ();
                //                break;
                //            case EventType.MouseMove:
                //                Debug.Log ("move");
                //                e.Use ();
                //                break;
                case EventType.DragPerform:
                    Debug.Log("DragPerform");
                    e.Use();
                    break;
                case EventType.DragUpdated:
                    Debug.Log("DragUpdated");
                    e.Use();
                    break;
                case EventType.DragExited:
                    Debug.Log("DragExited");
                    e.Use();
                    break;
            }
        };


        EditorApplication.hierarchyWindowItemOnGUI = delegate (int instanceID, Rect selectionRect) {

            OnEvent();

        };

        EditorApplication.projectWindowItemOnGUI = delegate (string guid, Rect selectionRect) {

            OnEvent();
        };

    }
}
View Code

7

Unity编辑器扩展学习 _第6张图片

using UnityEngine;
using UnityEditor;
using System.Collections;

public class MyHierarchyMenu {
    [MenuItem("Window/Test/yusong")]
    static void Test() {
    }

    [MenuItem("Window/Test/momo")]
    static void Test1() {
    }
    [MenuItem("Window/Test/雨松/MOMO")]
    static void Test2() {
    }


    [InitializeOnLoadMethod]
    static void StartInitializeOnLoadMethod() {
        EditorApplication.hierarchyWindowItemOnGUI += OnHierarchyGUI;
    }

    static void OnHierarchyGUI(int instanceID, Rect selectionRect) {
        if (Event.current != null && selectionRect.Contains(Event.current.mousePosition)
            && Event.current.button == 1 && Event.current.type <= EventType.MouseUp) {
            GameObject selectedGameObject = EditorUtility.InstanceIDToObject(instanceID) as GameObject;
            //这里可以判断selectedGameObject的条件
            if (selectedGameObject.name == "SceneRoot") {
                Vector2 mousePosition = Event.current.mousePosition;

                EditorUtility.DisplayPopupMenu(new Rect(mousePosition.x, mousePosition.y, 0, 0), "Window/Test", null);
                Event.current.Use();
            }
        }
    }

}
View Code

8

using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Reflection;
using UnityEngine.Profiling;

public class MyHierarchyMenu {
    [MenuItem("1/1")]
    public static void menu() {
        Texture target = Selection.activeObject as Texture;
        var type = System.Reflection.Assembly.Load("UnityEditor.dll").GetType("UnityEditor.TextureUtil");

        //var type = Types.GetType("UnityEditor.TextureUtil", "UnityEditor.dll");
        MethodInfo methodInfo = type.GetMethod("GetStorageMemorySize", BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public);

        Debug.Log("内存占用:" + EditorUtility.FormatBytes(Profiler.GetRuntimeMemorySizeLong(Selection.activeObject)));
        Debug.Log("硬盘占用:" + EditorUtility.FormatBytes((int)methodInfo.Invoke(null, new object[] { target })));
    }

}
View Code

 

你可能感兴趣的:(Unity编辑器扩展学习 )