Unity编辑器开发分享

[转]脚本的属性显示在自定义窗口下

2017-11-26  本文已影响7人  小小小小小丶敏

一般我们需要把脚本绑定在GameObject上,然后在Inspector视图下对其进行序列化编辑。假如我想把多个GameObject显示在一个自定义windows中怎么办呢?

这里我做了一个例子,把GameObject绑定在场景上,绑定在文件夹上。 呵呵~

如下图所示,我把Hierarcy视图中的gameObject拖到了场景上。然后就可以直接对其进行编辑了。

Unity3D研究院编辑器之脚本的属性显示在自定义窗口下(十八) - 雨松MOMO程序研究院 - 1

上代码

using UnityEngine;
using System.Collections;
using UnityEditor;
using UnityEditorInternal;
using System.Collections.Generic;
 
 
[CustomEditor (typeof(UnityEditor.DefaultAsset))]
 
public class CustomInspector : Editor
{
 
    List<Data> datas = new List<Data> ();
 
    public override void OnInspectorGUI ()
    {
        Event e = Event.current;
        string path = AssetDatabase.GetAssetPath (target);
 
        GUI.enabled = true;
        //if (path.EndsWith (".unity")) 
        {
            Draw();
            if (e.type == EventType.DragUpdated) {
                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                e.Use ();
            }
            if (e.type == EventType.DragPerform) {
 
                Object o1 = DragAndDrop.objectReferences [0];
                if (o1 is GameObject) {
                    datas.Add(new Data(){go = o1 as GameObject});
                }
            }
        }
    }
 
    Vector2 scrollPos = Vector2.zero;
    void Draw()
    {
 
        scrollPos = EditorGUILayout.BeginScrollView(scrollPos);
        foreach(Data data in datas)
        {
            var editor = Editor.CreateEditor (data.go);
            data.fold =EditorGUILayout.InspectorTitlebar (data.fold, data.go);
 
 
            if(data.fold)
            {
                editor.OnInspectorGUI ();
                GUILayout.BeginHorizontal();
                GUILayout.Space(20);
                GUILayout.BeginVertical();
                foreach (Component c in data.go.GetComponents<Component> ()) {
                    if (!data.editors.ContainsKey (c))
                        data.editors.Add (c, Editor.CreateEditor (c));
                } 
                foreach (Component c in data.go.GetComponents<Component> ()) {
                    if (data.editors.ContainsKey (c)) {
                        data.foldouts [c] = EditorGUILayout.InspectorTitlebar (data.foldouts.ContainsKey (c) ? data.foldouts [c] : true, c);
                        if (data.foldouts [c])
                            data.editors [c].OnInspectorGUI ();
                    }
                }
                GUILayout.EndVertical();
                GUILayout.EndHorizontal();
            }
        
        }
        EditorGUILayout.EndScrollView();
    }
 
    void OnInspectorUpdate ()
    {
        Repaint ();
    }
 
    class Data
    {
        public GameObject go;
        public bool fold = true;
        public Dictionary<Object , Editor> editors = new Dictionary<Object, Editor> ();
        public Dictionary<Object, bool> foldouts = new Dictionary<Object, bool> ();
    }
 
}
上一篇 下一篇

猜你喜欢

热点阅读