예제 #1
0
        protected virtual bool DrawWardrobeSlotsFields(Type TargetType, bool ShowHelp = false)
        {
            #region Setup
            bool doUpdate = false;
            //Field Infos
            FieldInfo ReplacesField             = TargetType.GetField("replaces", BindingFlags.Public | BindingFlags.Instance);
            FieldInfo CompatibleRacesField      = TargetType.GetField("compatibleRaces", BindingFlags.Public | BindingFlags.Instance);
            FieldInfo WardrobeSlotField         = TargetType.GetField("wardrobeSlot", BindingFlags.Public | BindingFlags.Instance);
            FieldInfo SuppressWardrobeSlotField = TargetType.GetField("suppressWardrobeSlots", BindingFlags.Public | BindingFlags.Instance);
            FieldInfo HidesField        = TargetType.GetField("Hides", BindingFlags.Public | BindingFlags.Instance);
            FieldInfo DisplayValueField = TargetType.GetField("DisplayValue", BindingFlags.Public | BindingFlags.Instance);
            FieldInfo UserField         = TargetType.GetField("UserField", BindingFlags.Public | BindingFlags.Instance);

            // ************************************
            // field values
            // ************************************
            string replaces = "";
            if (ReplacesField != null)
            {
                object o = ReplacesField.GetValue(target);
                if (o != null)
                {
                    replaces = (string)ReplacesField.GetValue(target);
                }
            }

            List <string> compatibleRaces      = (List <string>)CompatibleRacesField.GetValue(target);
            string        wardrobeSlot         = (string)WardrobeSlotField.GetValue(target);
            List <string> suppressWardrobeSlot = (List <string>)SuppressWardrobeSlotField.GetValue(target);
            List <string> hides          = (List <string>)HidesField.GetValue(target);
            string        displayValue   = (string)DisplayValueField.GetValue(target);
            string        userFieldValue = (string)UserField.GetValue(target);
            #endregion

            #region Display Value UI
            //displayValue UI
            string PreviousValue = displayValue;
            displayValue = EditorGUILayout.DelayedTextField("Display Value", displayValue);
            if (displayValue != PreviousValue)
            {
                DisplayValueField.SetValue(target, displayValue);
                doUpdate = true;
            }
            if (ShowHelp)
            {
                EditorGUILayout.HelpBox("Display Value can be used to store a user-friendly name for this item. It's not used for constructing the character, but it can be used in UI design by accessing the .DisplayValue field on the recipe.", MessageType.Info);
            }
            PreviousValue  = userFieldValue;
            userFieldValue = EditorGUILayout.DelayedTextField("User Field", userFieldValue);
            if (userFieldValue != PreviousValue)
            {
                UserField.SetValue(target, userFieldValue);
                doUpdate = true;
            }
            if (ShowHelp)
            {
                EditorGUILayout.HelpBox("User Field is ignored by the system. You can use this to store data that can later be used by your application to provide filtering or categorizing, etc.", MessageType.Info);
            }

            #endregion

            #region Wardrobe Slot UI
            //wardrobeSlot UI
            int           selectedWardrobeSlotIndex = GenerateWardrobeSlotsEnum(wardrobeSlot, compatibleRaces, false);
            string        newWardrobeSlot;
            int           newSuppressFlags        = 0;
            List <string> newSuppressWardrobeSlot = new List <string>();
            if (selectedWardrobeSlotIndex == -1)
            {
                EditorGUILayout.LabelField("No Compatible Races set. You need to select a compatible race in order to set a wardrobe slot");
                newWardrobeSlot = "None";
            }
            else if (selectedWardrobeSlotIndex == -2)
            {
                EditorGUILayout.LabelField("Not all compatible races found. Do you have the all correct Race(s) available Locally?");
                newWardrobeSlot = "None";
            }
            else
            {
                int newSelectedWardrobeSlotIndex = EditorGUILayout.Popup("Wardrobe Slot", selectedWardrobeSlotIndex, generatedWardrobeSlotOptionsLabels.ToArray());
                if (newSelectedWardrobeSlotIndex != selectedWardrobeSlotIndex)
                {
                    WardrobeSlotField.SetValue(target, generatedWardrobeSlotOptions[newSelectedWardrobeSlotIndex]);
                    doUpdate = true;
                }
                newWardrobeSlot = generatedWardrobeSlotOptions.Count > 0 ? generatedWardrobeSlotOptions[selectedWardrobeSlotIndex] : "None";
            }
            if (ShowHelp)
            {
                EditorGUILayout.HelpBox("Wardrobe Slot: This assigns the recipe to a Wardrobe Slot. The wardrobe slots are defined on the race. Characters can have only one recipe per Wardrobe Slot at a time, so for example, adding a 'beard' recipe to a character will replace the existing 'beard' if there is one", MessageType.Info);
            }
            #endregion

            #region Suppress UI
            //SuppressedSlots UI
            int suppressFlags = 0;
            for (int i = 0; i < generatedWardrobeSlotOptions.Count; i++)
            {
                if (suppressWardrobeSlot.Contains(generatedWardrobeSlotOptions[i]))
                {
                    suppressFlags |= 0x1 << i;
                }
            }
            newSuppressFlags = EditorGUILayout.MaskField("Suppress Wardrobe Slot(s)", suppressFlags, generatedWardrobeSlotOptionsLabels.ToArray());
            for (int i = 0; i < generatedWardrobeSlotOptions.Count; i++)
            {
                if ((newSuppressFlags & (1 << i)) == (1 << i))
                {
                    newSuppressWardrobeSlot.Add(generatedWardrobeSlotOptions[i]);
                }
            }
            if (newSuppressWardrobeSlot.Count > 1)
            {
                GUI.enabled = false;
                string swsl2Result = String.Join(", ", newSuppressWardrobeSlot.ToArray());
                EditorGUILayout.TextField(swsl2Result);
                GUI.enabled = true;
            }
            if (ShowHelp)
            {
                EditorGUILayout.HelpBox("Suppress: This will stop a different wardrobe slot from displaying. For example, if you have a full-length robe assigned to a 'chest' wardrobe slot, you would want to suppress whatever is assigned to the 'legs' wardrobe slot, so they don't poke through. This is typically used for dresses, robes, and other items that cover multiple body areas.", MessageType.Info);
            }
            #endregion

            #region Hides UI
            //Hides UI
            EditorGUILayout.BeginHorizontal();
            GenerateBaseSlotsEnum(compatibleRaces, false, hides);
            int           hiddenBaseFlags = 0;
            List <string> newHides        = new List <string>();
            for (int i = 0; i < generatedBaseSlotOptions.Count; i++)
            {
                if (hides.Contains(generatedBaseSlotOptions[i]))
                {
                    hiddenBaseFlags |= 0x1 << i;
                }
            }

            if (generatedBaseSlotOptionsLabels.Count > 0)
            {
                int newHiddenBaseFlags = 0;

                newHiddenBaseFlags = EditorGUILayout.MaskField("Hides Base Slot(s)", hiddenBaseFlags, generatedBaseSlotOptionsLabels.ToArray());
                for (int i = 0; i < generatedBaseSlotOptionsLabels.Count; i++)
                {
                    if ((newHiddenBaseFlags & (1 << i)) == (1 << i))
                    {
                        newHides.Add(generatedBaseSlotOptions[i]);
                    }
                }
            }
            else
            {
                EditorGUILayout.Popup("Hides Base Slots(s)", 0, new string[1] {
                    "Nothing"
                });
            }

            GUILayout.Space(8);
            if (GUILayout.Button("Select", GUILayout.MaxWidth(64), GUILayout.MaxHeight(16)))
            {
                slotHidePickerID = EditorGUIUtility.GetControlID(FocusType.Passive) + 101;
                EditorGUIUtility.ShowObjectPicker <SlotDataAsset>(null, false, "", slotHidePickerID);
            }
            if (Event.current.commandName == "ObjectSelectorUpdated" && EditorGUIUtility.GetObjectPickerControlID() == slotHidePickerID)
            {
                SlotDataAsset sda = EditorGUIUtility.GetObjectPickerObject() as SlotDataAsset;
                newHides.Add(sda.slotName);
                Event.current.Use();
                GenerateBaseSlotsEnum(compatibleRaces, true, hides);
            }

            EditorGUILayout.EndHorizontal();
            if (newHides.Count > 1)
            {
                GUI.enabled = false;
                string newHidesResult = String.Join(", ", newHides.ToArray());
                EditorGUILayout.TextField(newHidesResult);
                GUI.enabled = true;
            }

            if (ShowHelp)
            {
                EditorGUILayout.HelpBox("Hides: This is used to hide parts of the base recipe. For example, if you create gloves, you may want to hide the 'hands', so you don't get poke-through", MessageType.Info);
            }
            #endregion

            #region Replaces UI
            if (ReplacesField != null)
            {
                List <string> ReplacesSlots = new List <string>(generatedBaseSlotOptions);
                ReplacesSlots.Insert(0, "Nothing");
                int selectedIndex = ReplacesSlots.IndexOf(replaces);
                if (selectedIndex < 0)
                {
                    selectedIndex = 0;                                    // not found, point at "nothing"
                }
                selectedIndex = EditorGUILayout.Popup("Replaces", selectedIndex, ReplacesSlots.ToArray());

                ReplacesField.SetValue(target, ReplacesSlots[selectedIndex]);
            }

            if (ShowHelp)
            {
                EditorGUILayout.HelpBox("Replaces: This is used to replace part of the base recipe while keeping it's overlays. For example, if you want to replace the head from the base race recipe with a High Poly head, you would 'replace' the head, not hide it. Only one slot can be replaced, and the recipe should only contain one slot.", MessageType.Info);
            }
            #endregion

            #region MeshHideArray
            //EditorGUIUtility.LookLikeInspector();
            SerializedProperty meshHides = serializedObject.FindProperty("MeshHideAssets");
            EditorGUI.BeginChangeCheck();
            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("+", GUILayout.MaxWidth(30)))
            {
                meshHideAssetPickerID = EditorGUIUtility.GetControlID(FocusType.Passive) + 100;
                EditorGUIUtility.ShowObjectPicker <MeshHideAsset>(null, false, "", meshHideAssetPickerID);
            }
            GUILayout.Space(10);
            if (Event.current.commandName == "ObjectSelectorUpdated" && EditorGUIUtility.GetObjectPickerControlID() == meshHideAssetPickerID)
            {
                meshHides.InsertArrayElementAtIndex(0);
                SerializedProperty element = meshHides.GetArrayElementAtIndex(0);
                element.objectReferenceValue = EditorGUIUtility.GetObjectPickerObject();
                meshHideAssetPickerID        = -1;
            }
            EditorGUILayout.PropertyField(meshHides, true);
            EditorGUILayout.EndHorizontal();
            if (EditorGUI.EndChangeCheck())
            {
                serializedObject.ApplyModifiedProperties();
            }
            //EditorGUIUtility.LookLikeControls();
            if (ShowHelp)
            {
                EditorGUILayout.HelpBox("MeshHideAssets: This is a list of advanced mesh hiding assets to hide their corresponding slot meshes on a per triangle basis.", MessageType.Info);
            }
            #endregion

            #region Update
            //Update the values
            if (newWardrobeSlot != wardrobeSlot)
            {
                WardrobeSlotField.SetValue(target, newWardrobeSlot);
                doUpdate = true;
            }
            if (!AreListsEqual <string>(newSuppressWardrobeSlot, suppressWardrobeSlot))
            {
                SuppressWardrobeSlotField.SetValue(target, newSuppressWardrobeSlot);
                doUpdate = true;
            }
            if (!AreListsEqual <string>(newHides, hides))
            {
                HidesField.SetValue(target, newHides);
                doUpdate = true;
            }
            #endregion

            return(doUpdate);
        }
예제 #2
0
        public override void NeatWindow(  )
        {
            rect.height = TexAssetConnected() ? NODE_HEIGHT : NODE_HEIGHT + 34;

            GUI.skin.box.clipping = TextClipping.Overflow;
            GUI.BeginGroup(rect);

            if (IsProperty() && Event.current.type == EventType.DragPerform && rectInner.Contains(Event.current.mousePosition))
            {
                Object droppedObj = DragAndDrop.objectReferences[0];
                if (droppedObj is Texture2D /*|| droppedObj is ProceduralTexture */ || droppedObj is RenderTexture)
                {
                    Event.current.Use();
                    TextureAsset = droppedObj as Texture;
                    OnAssignedTexture();
                }
            }

            if (IsProperty() && Event.current.type == EventType.DragUpdated)
            {
                if (DragAndDrop.objectReferences.Length > 0)
                {
                    Object dragObj = DragAndDrop.objectReferences[0];
                    if (dragObj is Texture2D /*|| dragObj is ProceduralTexture*/ || dragObj is RenderTexture)
                    {
                        DragAndDrop.visualMode = DragAndDropVisualMode.Link;
                        editor.nodeBrowser.CancelDrag();
                        Event.current.Use();
                    }
                    else
                    {
                        DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
                    }
                }
                else
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
                }
            }



            Color prev = GUI.color;

            if (TextureAsset)
            {
                GUI.color = Color.white;
                GUI.DrawTexture(rectInner, texture.texture, ScaleMode.StretchToFill, false);                   // TODO: Doesn't seem to work
                if (displayVectorDataMask)
                {
                    GUI.DrawTexture(rectInner, SF_GUI.VectorIconOverlay, ScaleMode.ScaleAndCrop, true);
                }
            }

            if (showLowerPropertyBox && !TexAssetConnected())
            {
                GUI.color = Color.white;
                DrawLowerPropertyBox();
            }

            //else {
            //GUI.color = new Color( GUI.color.r, GUI.color.g, GUI.color.b,0.5f);
            //GUI.Label( rectInner, "Empty");
            //}
            GUI.color = prev;



            if (IsProperty())
            {
                bool draw = rectInner.Contains(Event.current.mousePosition) && !SF_NodeConnector.IsConnecting();

                Rect selectRect = new Rect(rectInner);
                selectRect.yMin += 80;
                selectRect.xMin += 40;
                Color c = GUI.color;
                GUI.color = new Color(1, 1, 1, draw ? 1 : 0);
                if (GUI.Button(selectRect, "Select", EditorStyles.miniButton))
                {
                    EditorGUIUtility.ShowObjectPicker <Texture>(TextureAsset, false, "", this.id);
                    Event.current.Use();
                }
                GUI.color = c;
            }


            if (IsProperty() && Event.current.type == EventType.ExecuteCommand && Event.current.commandName == "ObjectSelectorUpdated" && EditorGUIUtility.GetObjectPickerControlID() == this.id)
            {
                Event.current.Use();
                Texture newTextureAsset = EditorGUIUtility.GetObjectPickerObject() as Texture;
                if (newTextureAsset != TextureAsset)
                {
                    if (newTextureAsset == null)
                    {
                        UndoRecord("unassign texture of " + property.nameDisplay);
                    }
                    else
                    {
                        UndoRecord("switch texture to " + newTextureAsset.name + " in " + property.nameDisplay);
                    }
                    TextureAsset = newTextureAsset;
                    OnAssignedTexture();
                }
            }

            GUI.EndGroup();



            //	GUI.DragWindow();



            /*
             * EditorGUI.BeginChangeCheck();
             * textureAsset = (Texture)EditorGUI.ObjectField( rectInner, textureAsset, typeof( Texture ), false );
             * if( EditorGUI.EndChangeCheck() ) {
             *      OnAssignedTexture();
             * }
             * */
        }
        public void Step2()
        {
            EditorGUILayout.BeginVertical();
            EditorGUILayout.LabelField("Selected type: " + firstStepType.Name, (GUIStyle)"BoldLabel");


            var style = new GUIStyle(EditorStyles.boxStyle);

            style.alignment = TextAnchor.MiddleCenter;

            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("Cube (Default)", GUILayout.ExpandWidth(true), GUILayout.Height(30)) || step2Model == null)
            {
                // Use a box
                step2Model = GameObject.CreatePrimitive(PrimitiveType.Cube);
            }
            if (GUILayout.Button("None (Be warned...)", GUILayout.ExpandWidth(true), GUILayout.Height(30)))
            {
                step2Model = new GameObject("__Empty");
            }
            EditorGUILayout.EndHorizontal();
            if (GUILayout.Button("2D sprite with trigger", GUILayout.ExpandWidth(true), GUILayout.Height(30)))
            {
                // Use a box
                step2Model = new GameObject("2D Sprite");
                step2Model.GetOrAddComponent <SpriteRenderer>();
                var col = step2Model.GetOrAddComponent <BoxCollider2D>();
                col.isTrigger = true;
            }



            ShowOr();


            EditorGUILayout.BeginVertical();
            var boxStyle = new GUIStyle("HelpBox");

            boxStyle.stretchWidth = true;
            boxStyle.fixedHeight  = 200;
            boxStyle.alignment    = TextAnchor.MiddleCenter;
            var rect = GUILayoutUtility.GetRect(390, 390, 200, 200);

            rect.x    += 5;
            rect.width = 390;


            #region Accepting drag for box

            switch (Event.current.type)
            {
            case EventType.DragUpdated:
            case EventType.DragPerform:
                if (rect.Contains(Event.current.mousePosition) == false)
                {
                    break;
                }

                DragAndDrop.visualMode = DragAndDropVisualMode.Link;

                if (Event.current.type == EventType.DragPerform)
                {
                    if (DragAndDrop.objectReferences.Length == 1)
                    {
                        step2Model = DragAndDrop.objectReferences[0] as GameObject;
                        var sprite = DragAndDrop.objectReferences[0] as Sprite;

                        if (step2Model != null)
                        {
                            DragAndDrop.AcceptDrag();
                        }
                        else
                        {
                            if (sprite != null)
                            {
                                DragAndDrop.AcceptDrag();

                                step2Model = new GameObject("2D Sprite");
                                var spr = step2Model.GetOrAddComponent <SpriteRenderer>();
                                spr.sprite = sprite;

                                var col = step2Model.GetOrAddComponent <BoxCollider2D>();
                                col.isTrigger = true;
                            }
                        }
                    }
                }
                break;
            }

            #endregion


            if (step2Model == null)
            {
                GUI.Box(rect, "Drag object here", boxStyle);
            }
            else
            {
                var rect2 = rect;
                rect2.width /= 2;

                Texture2D preview = AssetPreview.GetAssetPreview(step2Model);
                if (preview != null)
                {
                    EditorGUI.DrawPreviewTexture(rect2, preview);

                    rect.width -= rect2.width;
                    rect.x     += rect2.width;
                }

                GUI.Box(rect, step2Model.name, boxStyle);
            }
            GUI.color = Color.white;


            ShowOr();


            if (Event.current.commandName == "ObjectSelectorUpdated")
            {
                if (EditorGUIUtility.GetObjectPickerControlID() == 123)
                {
                    step2Model = (GameObject)EditorGUIUtility.GetObjectPickerObject();
                    forceFocus = true;
                }
            }
            if (Event.current.commandName == "ObjectSelectorUpdated")
            {
                if (EditorGUIUtility.GetObjectPickerControlID() == 124)
                {
                    var sprite = (Sprite)EditorGUIUtility.GetObjectPickerObject();

                    step2Model = new GameObject("2D Sprite");
                    var spr = step2Model.GetOrAddComponent <SpriteRenderer>();
                    spr.sprite = sprite;

                    var col = step2Model.GetOrAddComponent <BoxCollider2D>();
                    col.isTrigger = true;

                    forceFocus = true;
                }
            }
            if (GUILayout.Button("Select model", GUILayout.ExpandWidth(true), GUILayout.Height(30)))
            {
                EditorGUIUtility.ShowObjectPicker <GameObject>(step2Model, false, "", 123);
                forceFocus = false;
            }
            if (GUILayout.Button("Select sprite", GUILayout.ExpandWidth(true), GUILayout.Height(30)))
            {
                EditorGUIUtility.ShowObjectPicker <Sprite>(step2Model, false, "", 124);
                forceFocus = false;
            }
            EditorGUILayout.EndVertical();

            if (step2Model == null)
            {
                GUI.enabled = false;
            }

            GUI.color = Color.green;
            if (GUILayout.Button("Create item", (GUIStyle)"LargeButton"))
            {
                if (step2Model != null)
                {
                    CreateItem(firstStepType, step2Model);
                }
            }
            GUI.color   = Color.white;
            GUI.enabled = true;

            EditorGUILayout.EndVertical();
        }
예제 #4
0
        public override void Draw(DrawInfo drawInfo)
        {
            base.Draw(drawInfo);

            if (m_editing)
            {
                m_textures = m_proceduralMaterial != null?m_proceduralMaterial.GetGeneratedTextures() : null;

                if (GUI.Button(m_pickerArea, string.Empty, GUIStyle.none))
                {
                    int controlID = EditorGUIUtility.GetControlID(FocusType.Passive);
                    EditorGUIUtility.ShowObjectPicker <ProceduralMaterial>(m_proceduralMaterial, false, "", controlID);
                }

                string             commandName = Event.current.commandName;
                UnityEngine.Object newValue    = null;
                if (commandName == "ObjectSelectorUpdated")
                {
                    newValue = EditorGUIUtility.GetObjectPickerObject();
                    if (newValue != (UnityEngine.Object)m_proceduralMaterial)
                    {
                        UndoRecordObject(this, "Changing value EditorGUIObjectField on node Substance Sample");

                        m_proceduralMaterial = newValue != null ? ( ProceduralMaterial )newValue : null;
                        m_textures           = m_proceduralMaterial != null?m_proceduralMaterial.GetGeneratedTextures() : null;

                        OnNewSubstanceSelected(m_textures);
                    }
                }
                else if (commandName == "ObjectSelectorClosed")
                {
                    newValue = EditorGUIUtility.GetObjectPickerObject();
                    if (newValue != (UnityEngine.Object)m_proceduralMaterial)
                    {
                        UndoRecordObject(this, "Changing value EditorGUIObjectField on node Substance Sample");

                        m_proceduralMaterial = newValue != null ? ( ProceduralMaterial )newValue : null;
                        m_textures           = m_proceduralMaterial != null?m_proceduralMaterial.GetGeneratedTextures() : null;

                        OnNewSubstanceSelected(m_textures);
                    }
                    m_editing = false;
                }

                if (GUI.Button(m_previewArea, string.Empty, GUIStyle.none))
                {
                    if (m_proceduralMaterial != null)
                    {
                        Selection.activeObject = m_proceduralMaterial;
                        EditorGUIUtility.PingObject(Selection.activeObject);
                    }
                    m_editing = false;
                }
            }

            if (drawInfo.CurrentEventType == EventType.Repaint)
            {
                if (!m_editing)
                {
                    m_textures = m_proceduralMaterial != null?m_proceduralMaterial.GetGeneratedTextures() : null;
                }

                if (m_textures != null)
                {
                    if (m_firstOutputConnected < 0)
                    {
                        CalculateFirstOutputConnected();
                    }
                    else if (m_textures.Length != m_textureTypes.Length)
                    {
                        OnNewSubstanceSelected(m_textures);
                    }

                    int  texCount    = m_outputConns.Count;
                    Rect individuals = m_previewArea;
                    individuals.height /= texCount;

                    for (int i = 0; i < texCount; i++)
                    {
                        EditorGUI.DrawPreviewTexture(individuals, m_textures[m_outputConns[i]], null, ScaleMode.ScaleAndCrop);
                        individuals.y += individuals.height;
                    }
                }
                else
                {
                    GUI.Label(m_previewArea, string.Empty, UIUtils.ObjectFieldThumb);
                }

                if (ContainerGraph.LodLevel <= ParentGraph.NodeLOD.LOD2)
                {
                    Rect smallButton = m_previewArea;
                    smallButton.height = 14 * drawInfo.InvertedZoom;
                    smallButton.y      = m_previewArea.yMax - smallButton.height - 2;
                    smallButton.width  = 40 * drawInfo.InvertedZoom;
                    smallButton.x      = m_previewArea.xMax - smallButton.width - 2;
                    if (m_textures == null)
                    {
                        GUI.Label(m_previewArea, "None (Procedural Material)", UIUtils.ObjectFieldThumbOverlay);
                    }
                    GUI.Label(m_pickerArea, "Select", UIUtils.GetCustomStyle(CustomStyle.SamplerButton));
                }

                GUI.Label(m_previewArea, string.Empty, UIUtils.GetCustomStyle(CustomStyle.SamplerFrame));
            }
        }
예제 #5
0
    private int controlID;                // The control ID for this track control.

    /// <summary>
    /// Header Control 3 is typically the "Add" control.
    /// </summary>
    /// <param name="position">The position that this control is drawn at.</param>
    protected override void updateHeaderControl5(UnityEngine.Rect position)
    {
        TimelineTrack track = TargetTrack.Behaviour as TimelineTrack;

        if (track == null)
        {
            return;
        }

        Color temp = GUI.color;

        GUI.color = (track.GetTimelineItems().Length > 0) ? Color.green : Color.red;

        controlID = GUIUtility.GetControlID(track.GetInstanceID(), FocusType.Passive);

        if (GUI.Button(position, string.Empty, TrackGroupControl.styles.addIcon))
        {
            // Get the possible items that this track can contain.
            List <Type> trackTypes = track.GetAllowedCutsceneItems();

            if (trackTypes.Count == 1)
            {
                // Only one option, so just create it.
                ContextData data = getContextData(trackTypes[0]);
                if (data.PairedType == null)
                {
                    addCutsceneItem(data);
                }
                else
                {
                    showObjectPicker(data);
                }
            }
            else if (trackTypes.Count > 1)
            {
                // Present context menu for selection.
                GenericMenu createMenu = new GenericMenu();
                foreach (Type t in trackTypes)
                {
                    ContextData data = getContextData(t);

                    createMenu.AddItem(new GUIContent(string.Format("{0}/{1}", data.Category, data.Label)), false, addCutsceneItem, data);
                }
                createMenu.ShowAsContext();
            }
        }

        // Handle the case where the object picker has a value selected.
        if (Event.current.type == EventType.ExecuteCommand && Event.current.commandName == "ObjectSelectorClosed")
        {
            if (EditorGUIUtility.GetObjectPickerControlID() == controlID)
            {
                UnityEngine.Object pickedObject = EditorGUIUtility.GetObjectPickerObject();

                if (pickedObject != null)
                {
                    addCutsceneItem(savedData, pickedObject);
                }

                Event.current.Use();
            }
        }

        GUI.color = temp;
    }
예제 #6
0
        public override void OnInspectorGUI()
        {
            MixedRealityToolkit instance = (MixedRealityToolkit)target;

            if (MixedRealityToolkit.Instance == null && instance.isActiveAndEnabled)
            {   // See if an active instance exists at all. If it doesn't register this instance preemptively.
                MixedRealityToolkit.SetActiveInstance(instance);
            }

            if (!instance.IsActiveInstance)
            {
                EditorGUILayout.HelpBox("This instance of the toolkit is inactive. There can only be one active instance loaded at any time.", MessageType.Warning);
                EditorGUILayout.BeginHorizontal();
                if (GUILayout.Button("Select Active Instance"))
                {
                    UnityEditor.Selection.activeGameObject = MixedRealityToolkit.Instance.gameObject;
                }
                if (GUILayout.Button("Make this the Active Instance"))
                {
                    MixedRealityToolkit.SetActiveInstance(instance);
                }
                EditorGUILayout.EndHorizontal();
                return;
            }

            serializedObject.Update();
            EditorGUI.BeginChangeCheck();
            EditorGUILayout.PropertyField(activeProfile);
            bool   changed     = EditorGUI.EndChangeCheck();
            string commandName = Event.current.commandName;

            // If not profile is assigned, then warn user
            if (activeProfile.objectReferenceValue == null)
            {
                EditorGUILayout.HelpBox("MixedRealityToolkit cannot initialize unless an Active Profile is assigned!", MessageType.Error);

                if (GUILayout.Button("Assign MixedRealityToolkit Profile") || forceShowProfilePicker)
                {
                    forceShowProfilePicker = false;

                    var allConfigProfiles = ScriptableObjectExtensions.GetAllInstances <MixedRealityToolkitConfigurationProfile>();

                    // Shows the list of MixedRealityToolkitConfigurationProfiles in our project,
                    // selecting the default profile by default (if it exists).
                    if (allConfigProfiles.Length > 0)
                    {
                        currentPickerWindow = GUIUtility.GetControlID(FocusType.Passive);

                        var defaultMRTKProfile = MixedRealityInspectorUtility.GetDefaultConfigProfile(allConfigProfiles);
                        activeProfile.objectReferenceValue = defaultMRTKProfile;

                        EditorGUIUtility.ShowObjectPicker <MixedRealityToolkitConfigurationProfile>(defaultMRTKProfile, false, string.Empty, currentPickerWindow);
                    }
                    else
                    {
                        if (EditorUtility.DisplayDialog("Attention!", "No profiles were found for the Mixed Reality Toolkit.\n\n" +
                                                        "Would you like to create one now?", "OK", "Later"))
                        {
                            ScriptableObject profile = CreateInstance(nameof(MixedRealityToolkitConfigurationProfile));
                            profile.CreateAsset("Assets/MixedRealityToolkit.Generated/CustomProfiles");
                            activeProfile.objectReferenceValue = profile;
                            EditorGUIUtility.PingObject(profile);
                        }
                    }
                }
            }

            // If user selects a new MRTK Active Profile, then update configuration
            if (EditorGUIUtility.GetObjectPickerControlID() == currentPickerWindow)
            {
                switch (commandName)
                {
                case "ObjectSelectorUpdated":
                    activeProfile.objectReferenceValue = EditorGUIUtility.GetObjectPickerObject();
                    changed = true;
                    break;

                case "ObjectSelectorClosed":
                    activeProfile.objectReferenceValue = EditorGUIUtility.GetObjectPickerObject();
                    currentPickerWindow = -1;
                    changed             = true;
                    break;
                }
            }

            serializedObject.ApplyModifiedProperties();

            if (changed)
            {
                MixedRealityToolkit.Instance.ResetConfiguration((MixedRealityToolkitConfigurationProfile)activeProfile.objectReferenceValue);
            }

            if (activeProfile.objectReferenceValue != null)
            {
                UnityEditor.Editor activeProfileEditor = CreateEditor(activeProfile.objectReferenceValue);
                activeProfileEditor.OnInspectorGUI();
            }
        }
예제 #7
0
        public override void NeatWindow(  )
        {
            GUI.skin.box.clipping = TextClipping.Overflow;
            GUI.BeginGroup(rect);

            if (IsGlobalProperty())
            {
                GUI.enabled = false;
            }

            if (IsProperty() && Event.current.type == EventType.DragPerform && rectInner.Contains(Event.current.mousePosition))
            {
                Object droppedObj = DragAndDrop.objectReferences[0];
#if UNITY_2018
                if (droppedObj is Texture2D || droppedObj is RenderTexture)
                {
#else
                if (droppedObj is Texture2D || droppedObj is ProceduralTexture || droppedObj is RenderTexture)
                {
#endif
                    Event.current.Use();
                    textureAsset = droppedObj as Texture;
                    OnAssignedTexture();
                }
            }

#if UNITY_2018
            if (IsProperty() && Event.current.type == EventType.DragUpdated)
            {
#else
            if (IsProperty() && Event.current.type == EventType.dragUpdated)
            {
#endif
                if (DragAndDrop.objectReferences.Length > 0)
                {
                    Object dragObj = DragAndDrop.objectReferences[0];
#if UNITY_2018
                    if (dragObj is Texture2D || dragObj is RenderTexture)
                    {
#else
                    if (dragObj is Texture2D || dragObj is ProceduralTexture || dragObj is RenderTexture)
                    {
#endif
                        DragAndDrop.visualMode = DragAndDropVisualMode.Link;
                        editor.nodeBrowser.CancelDrag();
                        Event.current.Use();
                    }
                    else
                    {
                        DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
                    }
                }
                else
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
                }
            }

            if (IsGlobalProperty())
            {
                GUI.enabled = true;
            }



            Color prev = GUI.color;
            if (textureAsset)
            {
                GUI.color = Color.white;
                GUI.DrawTexture(rectInner, texture.texture, ScaleMode.StretchToFill, false);
            }             //else {
                          //GUI.color = new Color( GUI.color.r, GUI.color.g, GUI.color.b,0.5f);
                          //GUI.Label( rectInner, "Empty");
                          //}

            if (showLowerPropertyBox)
            {
                GUI.color = Color.white;
                DrawLowerPropertyBox();
            }

            GUI.color = prev;



            if (rectInner.Contains(Event.current.mousePosition) && !SF_NodeConnector.IsConnecting() && !IsGlobalProperty())
            {
                Rect selectRect = new Rect(rectInner);
                selectRect.yMin += 80;
                selectRect.xMin += 40;

                if (GUI.Button(selectRect, "Select", EditorStyles.miniButton))
                {
                    EditorGUIUtility.ShowObjectPicker <Texture>(textureAsset, false, "", this.id);
                    Event.current.Use();
                }
            }


            if (!IsGlobalProperty() && Event.current.type == EventType.ExecuteCommand && Event.current.commandName == "ObjectSelectorUpdated" && EditorGUIUtility.GetObjectPickerControlID() == this.id)
            {
                Event.current.Use();
                Texture newTextureAsset = EditorGUIUtility.GetObjectPickerObject() as Texture;
                if (newTextureAsset != textureAsset)
                {
                    if (newTextureAsset == null)
                    {
                        UndoRecord("unassign texture of " + property.nameDisplay);
                    }
                    else
                    {
                        UndoRecord("switch texture to " + newTextureAsset.name + " in " + property.nameDisplay);
                    }
                    textureAsset = newTextureAsset;
                    OnAssignedTexture();
                }
            }

            GUI.EndGroup();



            //	GUI.DragWindow();



            /*
             * EditorGUI.BeginChangeCheck();
             * textureAsset = (Texture)EditorGUI.ObjectField( rectInner, textureAsset, typeof( Texture ), false );
             * if( EditorGUI.EndChangeCheck() ) {
             *      OnAssignedTexture();
             * }
             * */
        }
예제 #8
0
        public override void OnInspectorGUI()
        {
            serializedObject.Update();
            EditorGUI.BeginChangeCheck();
            EditorGUILayout.PropertyField(activeProfile);
            bool   changed           = EditorGUI.EndChangeCheck();
            string commandName       = Event.current.commandName;
            var    allConfigProfiles = ScriptableObjectExtensions.GetAllInstances <MixedRealityToolkitConfigurationProfile>();

            if (activeProfile.objectReferenceValue == null && currentPickerWindow == -1 && checkChange)
            {
                if (allConfigProfiles.Length > 1)
                {
                    EditorUtility.DisplayDialog("Attention!", "You must choose a profile for the Mixed Reality Toolkit.", "OK");
                    currentPickerWindow = GUIUtility.GetControlID(FocusType.Passive);
                    EditorGUIUtility.ShowObjectPicker <MixedRealityToolkitConfigurationProfile>(null, false, string.Empty, currentPickerWindow);
                }
                else if (allConfigProfiles.Length == 1)
                {
                    activeProfile.objectReferenceValue = allConfigProfiles[0];
                    changed = true;
                    Selection.activeObject = allConfigProfiles[0];
                    EditorGUIUtility.PingObject(allConfigProfiles[0]);
                }
                else
                {
                    if (EditorUtility.DisplayDialog("Attention!", "No profiles were found for the Mixed Reality Toolkit.\n\n" +
                                                    "Would you like to create one now?", "OK", "Later"))
                    {
                        ScriptableObject profile = CreateInstance(nameof(MixedRealityToolkitConfigurationProfile));
                        profile.CreateAsset("Assets/MixedRealityToolkit.Generated/CustomProfiles");
                        activeProfile.objectReferenceValue = profile;
                        Selection.activeObject             = profile;
                        EditorGUIUtility.PingObject(profile);
                    }
                }

                checkChange = false;
            }

            if (EditorGUIUtility.GetObjectPickerControlID() == currentPickerWindow)
            {
                switch (commandName)
                {
                case "ObjectSelectorUpdated":
                    activeProfile.objectReferenceValue = EditorGUIUtility.GetObjectPickerObject();
                    changed = true;
                    break;

                case "ObjectSelectorClosed":
                    activeProfile.objectReferenceValue = EditorGUIUtility.GetObjectPickerObject();
                    currentPickerWindow    = -1;
                    changed                = true;
                    Selection.activeObject = activeProfile.objectReferenceValue;
                    EditorGUIUtility.PingObject(activeProfile.objectReferenceValue);
                    break;
                }
            }

            serializedObject.ApplyModifiedProperties();

            if (changed)
            {
                MixedRealityToolkit.Instance.ResetConfiguration((MixedRealityToolkitConfigurationProfile)activeProfile.objectReferenceValue);
            }

            if (activeProfile.objectReferenceValue != null)
            {
                UnityEditor.Editor activeProfileEditor = CreateEditor(activeProfile.objectReferenceValue);
                activeProfileEditor.OnInspectorGUI();
            }
        }
예제 #9
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            var dataTypeProperty  = property.FindPropertyRelative("dataType");
            var iconTypeProperty  = property.FindPropertyRelative("iconType");
            var nameProperty      = property.FindPropertyRelative("name");
            var pathProperty      = property.FindPropertyRelative("path");
            var tooltipProperty   = property.FindPropertyRelative("tooltip");
            var largeIconProperty = property.FindPropertyRelative("largeIcon");
            var smallIconProperty = property.FindPropertyRelative("smallIcon");
            var iconNameProperty  = property.FindPropertyRelative("iconName");

            var isPathBased  = dataTypeProperty.intValue == 0;
            var propertyName = isPathBased
                ? pathProperty.stringValue
                : nameProperty.stringValue;

            //begin the main property
            label      = EditorGUI.BeginProperty(position, label, property);
            label.text = string.IsNullOrEmpty(propertyName) ? label.text : propertyName;

            var propertyPosition = new Rect(position.x, position.y, position.width, Style.height);

            if (!(property.isExpanded = EditorGUI.Foldout(propertyPosition, property.isExpanded, label, true, Style.propertyFoldoutStyle)))
            {
                EditorGUI.EndProperty();

                //adjust position for small icon and draw it in label field
                var typeIconRect = new Rect(position.xMax - Style.smallFolderWidth,
#if UNITY_2019_3_OR_NEWER
                                            position.yMin,
                                            Style.smallFolderWidth,
                                            Style.smallFolderHeight);
#else
                                            position.yMin - Style.spacing,
                                            Style.smallFolderWidth,
                                            Style.smallFolderHeight);
#endif
                if (isPathBased)
                {
                    //NOTE: if path property is bigger than typical row height it means that associated value is invalid
                    var isValid = EditorGUI.GetPropertyHeight(pathProperty) <= Style.height;
                    if (isValid)
                    {
                        DrawFolderByPathIcon(typeIconRect);
                    }
                    else
                    {
                        DrawLabelWarningIcon(typeIconRect);
                    }
                }
                else
                {
                    DrawFolderByNameIcon(typeIconRect);
                }

                return;
            }

            EditorGUI.indentLevel++;

            var rawPropertyHeight  = propertyPosition.height + Style.spacing;
            var summaryFieldHeight = rawPropertyHeight;

            propertyPosition.y += rawPropertyHeight;
            summaryFieldHeight += rawPropertyHeight;
            //draw the folder data type property
            EditorGUI.PropertyField(propertyPosition, dataTypeProperty, new GUIContent("Type"), false);
            propertyPosition.y += rawPropertyHeight;
            summaryFieldHeight += rawPropertyHeight;

            //decide what property should be drawn depending on the folder data type
            if (isPathBased)
            {
                propertyPosition.height = EditorGUI.GetPropertyHeight(pathProperty);
                EditorGUI.PropertyField(propertyPosition, pathProperty, false);
                propertyPosition.y     += propertyPosition.height + Style.spacing;
                summaryFieldHeight     += propertyPosition.height + Style.spacing;
                propertyPosition.height = Style.height;
            }
            else
            {
                EditorGUI.PropertyField(propertyPosition, nameProperty, false);
                propertyPosition.y += rawPropertyHeight;
                summaryFieldHeight += rawPropertyHeight;
            }

            propertyPosition.height = EditorGUI.GetPropertyHeight(tooltipProperty);
            EditorGUI.PropertyField(propertyPosition, tooltipProperty, false);
            propertyPosition.y     += propertyPosition.height + Style.spacing;
            summaryFieldHeight     += propertyPosition.height + Style.spacing;
            propertyPosition.height = Style.height;

            //adjust rect for folder icons + button strip
            propertyPosition.y    += Style.spacing;
            propertyPosition.x    += Style.padding;
            propertyPosition.width = Style.largeFolderWidth;

            var selectorHash = GetSelectorHash(property);
            //draw large icon property picker
            if (GUI.Button(propertyPosition, Style.largeIconPickerContent, Style.largeIconPickerStyle))
            {
                EditorGUIUtility.ShowObjectPicker <Texture>(largeIconProperty.objectReferenceValue, false, null, selectorHash + largeIconPickedId);
            }

            propertyPosition.xMin = propertyPosition.xMax;
            propertyPosition.xMax = propertyPosition.xMin + Style.smallFolderWidth;
            position.x           += Style.padding;

            //draw small icon property picker
            if (GUI.Button(propertyPosition, Style.smallIconPickerContent, Style.smallIconPickerStyle))
            {
                EditorGUIUtility.ShowObjectPicker <Texture>(smallIconProperty.objectReferenceValue, false, null, selectorHash + smallIconPickedId);
            }

            //catch object selection event and assign it to proper property
            if (Event.current.commandName == "ObjectSelectorUpdated")
            {
                //get proper action id by removing unique property hash code
                var rawPickId = EditorGUIUtility.GetObjectPickerControlID();
                var controlId = rawPickId - selectorHash;
                //determine the target property using predefined values
                SerializedProperty iconProperty = null;
                switch (controlId)
                {
                case largeIconPickedId:
                    iconProperty = largeIconProperty;
                    break;

                case smallIconPickedId:
                    iconProperty = smallIconProperty;
                    break;
                }

                //update the previously picked property
                if (iconProperty != null)
                {
                    var o = EditorGUIUtility.GetObjectPickerObject();
                    iconProperty.serializedObject.Update();
                    iconProperty.objectReferenceValue = o;
                    iconProperty.serializedObject.ApplyModifiedProperties();
                    //force GUI to changed state
                    GUI.changed = true;
                }
            }

            var largeIcon = largeIconProperty.objectReferenceValue as Texture;
            var smallIcon = smallIconProperty.objectReferenceValue as Texture;
            DrawFolderIconsStrip(position, largeIcon, smallIcon);
            EditorGUI.indentLevel--;
            EditorGUI.EndProperty();
        }
        public override void OnInspectorGUI()
        {
            if (target == null)
            {
                return;
            }

            var proCamera2DShake = (ProCamera2DShake)target;

            if (proCamera2DShake.ProCamera2D == null)
            {
                EditorGUILayout.HelpBox("ProCamera2D is not set.", MessageType.Error, true);
            }

            serializedObject.Update();

            // Show script link
            GUI.enabled = false;
            _script     = EditorGUILayout.ObjectField("Script", _script, typeof(MonoScript), false) as MonoScript;
            GUI.enabled = true;

            // ProCamera2D
            _tooltip = new GUIContent("Pro Camera 2D", "");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("ProCamera2D"), _tooltip);

            EditorGUILayout.Space();
            EditorGUILayout.Space();

            // Create ShakePreset button
            if (GUILayout.Button("Create ShakePreset"))
            {
                Undo.RecordObject(proCamera2DShake, "Added shake preset");

                proCamera2DShake.ShakePresets.Add(ScriptableObjectUtility.CreateAsset <ShakePreset>("ShakePreset"));
            }

            // Shake Presets list
            EditorGUILayout.Space();
            _shakePresetsList.DoLayoutList();

            // ShakePreset selected from picker window
            if (Event.current.commandName == "ObjectSelectorUpdated" && EditorGUIUtility.GetObjectPickerControlID() == _currentPickerWindow)
            {
                var preset = EditorGUIUtility.GetObjectPickerObject() as ShakePreset;

                if (preset != null)
                {
                    if (!proCamera2DShake.ShakePresets.Contains(preset))
                    {
                        Undo.RecordObject(proCamera2DShake, "Added shake preset");

                        proCamera2DShake.ShakePresets.Add(preset);
                    }
                }
            }

            EditorGUILayout.Space();
            EditorGUILayout.Space();

            // Create ConstantShakePreset button
            if (GUILayout.Button("Create ConstantShakePreset"))
            {
                Undo.RecordObject(proCamera2DShake, "Added shake preset");

                ScriptableObjectUtility.CreateAsset <ConstantShakePreset>("ConstantShakePreset");
            }

            // ConstantShake Presets list
            EditorGUILayout.Space();
            _constantShakePresetsList.DoLayoutList();

            // ConstantShakePreset selected from picker window
            if (Event.current.commandName == "ObjectSelectorUpdated" && EditorGUIUtility.GetObjectPickerControlID() == _currentPickerWindow)
            {
                var preset = EditorGUIUtility.GetObjectPickerObject() as ConstantShakePreset;

                if (preset != null)
                {
                    if (!proCamera2DShake.ConstantShakePresets.Contains(preset))
                    {
                        Undo.RecordObject(proCamera2DShake, "Added shake preset");

                        proCamera2DShake.ConstantShakePresets.Add(preset);
                    }
                }
            }

            // Save changes
            serializedObject.ApplyModifiedProperties();
        }
예제 #11
0
    void DetailPart()
    {
        GUILayout.BeginVertical();


        #region Icon & Detail

        GUILayout.BeginHorizontal();

        #region Icon Part

        if (temp.icon != null)
        {
            ItemIcon = temp.icon.texture;
        }


        if (GUILayout.Button(ItemIcon, GUILayout.Width(IconButtonSize.x), GUILayout.Height(IconButtonSize.y)))
        {
            EditorGUIUtility.ShowObjectPicker <Sprite>(null, true, null, 0);
        }
        string commend = Event.current.commandName;
        if (commend == "ObjectSelectorClosed")
        {
            temp.icon = (Sprite)EditorGUIUtility.GetObjectPickerObject();
        }

        #endregion

        #region Detail Part

        GUILayout.BeginVertical();

        #region Name & Game Object

        GUILayout.BeginHorizontal();

        GUILayout.Label("Item Name:");
        temp.name = GUILayout.TextField(temp.name, GUILayout.Width(200));

        GUILayout.Label("Item Shape:");
        temp.visual = EditorGUILayout.ObjectField(temp.visual, typeof(GameObject)) as GameObject;

        GUILayout.EndHorizontal();

        #endregion

        #region Damage , Hit Point & Type
        GUILayout.BeginHorizontal();

        //Damage
        temp.damage = EditorGUILayout.FloatField("Damage:", temp.damage);
        //HitPoint
        temp.hitPoint = EditorGUILayout.FloatField("Hit Point:", temp.hitPoint);
        //type
        temp.itemType = (ItemType)EditorGUILayout.EnumPopup("Item Type:", temp.itemType);

        GUILayout.EndHorizontal();
        #endregion

        GUILayout.EndVertical();

        #endregion



        GUILayout.EndHorizontal();

        #endregion


        GUILayout.Label("Item Description:");
        temp.description = EditorGUILayout.TextArea(temp.description, GUILayout.ExpandHeight(true), GUILayout.ExpandWidth(true));


        GUILayout.EndVertical();
    }
예제 #12
0
    // Called to draw the MapEditor windows.
    private void OnGUI()
    {
        active = true;
        EditorGUILayout.BeginHorizontal();
        width  = EditorGUILayout.IntField("Width", width);
        height = EditorGUILayout.IntField("Height", height);

        EditorGUILayout.EndHorizontal();
        if (GUILayout.Button("Generate map"))
        {
            GenerateMap();
        }
        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("Place tile");
        objectType = EditorGUILayout.Popup(objectType, Enum.GetNames(typeof(PlacebleObjects)));
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        if (GUILayout.Button("Save map"))
        {
            if (mapSaveName != "")
            {
                SaveMap();
            }
        }
        mapSaveName = EditorGUILayout.TextField(mapSaveName);
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        if (GUILayout.Button("Load map"))
        {
            int controlID = GUIUtility.GetControlID(FocusType.Passive);
            EditorGUIUtility.ShowObjectPicker <MapSO>(loadMap, false, "", controlID);
            loadedClicked = true;
        }

        EditorGUILayout.EndHorizontal();


        if (Event.current.commandName == "ObjectSelectorClosed")
        {
            loadMap = (MapSO)EditorGUIUtility.GetObjectPickerObject();
            if (loadMap != null && loadedClicked)
            {
                loadedClicked = false;

                LoadMap();
            }
        }

        foldouts[(int)FoldoutsName.QUICK_ACTIONS] = EditorGUILayout.Foldout(foldouts[(int)FoldoutsName.QUICK_ACTIONS], "Actions");
        if (foldouts[(int)FoldoutsName.QUICK_ACTIONS])
        {
            if (GUILayout.Button("Flatten"))
            {
                for (int x = 0; x < width; x++)
                {
                    for (int z = 0; z < height; z++)
                    {
                        mapArray[x, z].GetComponent <FloorTile>().IsWalkable = true;
                    }
                }
            }
            if (GUILayout.Button("Outer wall"))
            {
                for (int x = 0; x < width; x++)
                {
                    for (int z = 0; z < height; z++)
                    {
                        if (x == 0 || x == width - 1 || z == 0 || z == height - 1)
                        {
                            mapArray[x, z].GetComponent <FloorTile>().IsWalkable = false;
                        }
                    }
                }
            }
        }
    }
 public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
 {
     if (property.propertyType != SerializedPropertyType.String && property.propertyType != SerializedPropertyType.ObjectReference)
     {
         EditorGUI.LabelField(position, label, new GUIContent("only support string or object ref"));
         return;
     }
     base.OnGUI(position, property, label);
     label = EditorGUI.BeginProperty(position, label, property);
     // 入力フィールド域サイズ
     position.width = EditorGUIUtility.labelWidth + (fullWidth - EditorGUIUtility.labelWidth) * 0.75f;
     EditorGUI.PropertyField(position, property, label);
     // 選択サイズ
     position.xMin  = position.xMax + 5;
     position.width = fullWidth - position.xMin;
     if (GUI.Button(position, "Picker"))
     {
         var method      = typeof(EditorGUIUtility).GetMethod("ShowObjectPicker");
         var constructed = method.MakeGenericMethod(Attribute.type);
         controlId = GUIUtility.GetControlID(label, FocusType.Passive, position);
         if (controlId == -1)
         {
             controlId = (int)UnityEngine.Random.Range(int.MinValue, int.MaxValue);
         }
         // Debug.Log(controlId);
         constructed.Invoke(null, new object[] { null, Attribute.allowSceneObjects, Attribute.filter, controlId });
     }
     if (Event.current.commandName == "ObjectSelectorUpdated" && EditorGUIUtility.GetObjectPickerControlID() == controlId)
     {
         var selected = EditorGUIUtility.GetObjectPickerObject();
         // currentPickerWindow = -1;
         if (selected != null)
         {
             // string case
             if (property.propertyType == SerializedPropertyType.String)
             {
                 string path = "";
                 if (!Attribute.allowSceneObjects)
                 {
                     path = AssetDatabase.GetAssetOrScenePath((UnityEngine.Object)selected);
                     // var ext = Path.GetExtension(path);
                     // only filename
                     if (Attribute.onlyFilename)
                     {
                         path = Path.GetFileName(path);
                     }
                     // extension
                     if (!Attribute.extension)
                     {
                         path = path.Split('.')[0];
                     }
                 }
                 else
                 {
                     path = selected.name;
                 }
                 // replace
                 if (Attribute.replaceFrom != null)
                 {
                     path = path.Replace(Attribute.replaceFrom, Attribute.replaceTo ?? "");
                 }
                 property.stringValue = path;
             }
             // ref case
             else if (property.propertyType == SerializedPropertyType.ObjectReference)
             {
                 property.objectReferenceValue = selected;
             }
         }
     }
     EditorGUI.EndProperty();
 }
예제 #14
0
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        int newGraphIndex = EditorGUILayout.Popup(graphIndex, graphNames.ToArray <string>());

        if (newGraphIndex >= 0 && newGraphIndex != graphIndex)
        {
            graphIndex      = newGraphIndex;
            graphNode.graph = graphs[graphNames[graphIndex]];
        }

        int toolbarButton = GUILayout.Toolbar(-1, new string[] { "+", "-" });

        if (toolbarButton == 0)
        {
            selectedAddLinkObjectFrom = graphNode;
            EditorGUIUtility.ShowObjectPicker <GraphNode>(null, true, "", 0);
        }

        if (Event.current.commandName == "ObjectSelectorUpdated")
        {
            selectedAddLinkObjectTo = EditorGUIUtility.GetObjectPickerObject() as GameObject;
            SceneView.RepaintAll();
        }
        if (Event.current.commandName == "ObjectSelectorClosed")
        {
            if (selectedAddLinkObjectFrom != null && selectedAddLinkObjectFrom != selectedAddLinkObjectTo)
            {
                GraphNode nodeFrom = selectedAddLinkObjectFrom;
                GraphNode nodeTo   = null;

                foreach (GraphNode nodeToCandidate in selectedAddLinkObjectTo.GetComponents <GraphNode>())
                {
                    if (nodeToCandidate.graph == nodeFrom.graph)
                    {
                        nodeTo = nodeToCandidate;
                        break;
                    }
                }

                if (nodeTo == null)
                {
                    bool result = EditorUtility.DisplayDialog("Add new GraphNode component to an Object?"
                                                              , "GameObject does not have GraphNode component belonging to a Graph. Should I add a new GraphNode component to the GameObject?"
                                                              , "Add", "Do not add");
                    if (result)
                    {
                        nodeTo       = selectedAddLinkObjectTo.gameObject.AddComponent <GraphNode>();
                        nodeTo.graph = nodeFrom.graph;
                    }
                }

                nodeFrom.LinkToNode(nodeTo);
            }

            selectedAddLinkObjectFrom = null;
            selectedAddLinkObjectTo   = null;
            SceneView.RepaintAll();
        }
    }
예제 #15
0
        public static void drawStylizedBigTextureProperty(Rect position, MaterialProperty prop, GUIContent label, MaterialEditor editor, bool hasFoldoutProperties, bool skip_drag_and_drop_handling = false)
        {
            position.x     += (EditorGUI.indentLevel) * 15;
            position.width -= (EditorGUI.indentLevel) * 15;
            Rect rect = GUILayoutUtility.GetRect(label, Styles.bigTextureStyle);

            rect.x     += (EditorGUI.indentLevel) * 15;
            rect.width -= (EditorGUI.indentLevel) * 15;
            Rect border = new Rect(rect);

            border.position = new Vector2(border.x, border.y - position.height);
            border.height  += position.height;

            if (DrawingData.currentTexProperty.reference_properties_exist)
            {
                border.height += 8;
                foreach (string r_property in DrawingData.currentTexProperty.options.reference_properties)
                {
                    border.height += editor.GetPropertyHeight(ShaderEditor.active.propertyDictionary[r_property].materialProperty);
                }
            }
            if (DrawingData.currentTexProperty.reference_property_exists)
            {
                border.height += 8;
                border.height += editor.GetPropertyHeight(ShaderEditor.active.propertyDictionary[DrawingData.currentTexProperty.options.reference_property].materialProperty);
            }


            //background
            GUI.DrawTexture(border, Styles.rounded_texture, ScaleMode.StretchToFill, true);
            Rect quad = new Rect(border);

            quad.width = quad.height / 2;
            GUI.DrawTextureWithTexCoords(quad, Styles.rounded_texture, new Rect(0, 0, 0.5f, 1), true);
            quad.x += border.width - quad.width;
            GUI.DrawTextureWithTexCoords(quad, Styles.rounded_texture, new Rect(0.5f, 0, 0.5f, 1), true);

            quad.width  = border.height - 4;
            quad.height = quad.width;
            quad.x      = border.x + border.width - quad.width - 1;
            quad.y     += 2;

            DrawingData.currentTexProperty.tooltip.ConditionalDraw(border);

            Rect preview_rect_border = new Rect(position);

            preview_rect_border.height = rect.height + position.height - 6;
            preview_rect_border.width  = preview_rect_border.height;
            preview_rect_border.y     += 3;
            preview_rect_border.x     += position.width - preview_rect_border.width - 3;
            Rect preview_rect = new Rect(preview_rect_border);

            preview_rect.height -= 6;
            preview_rect.width  -= 6;
            preview_rect.x      += 3;
            preview_rect.y      += 3;
            if (prop.hasMixedValue)
            {
                Rect mixedRect = new Rect(preview_rect);
                mixedRect.y -= 5;
                mixedRect.x += mixedRect.width / 2 - 4;
                GUI.Label(mixedRect, "_");
            }
            else if (prop.textureValue != null)
            {
                GUI.DrawTexture(preview_rect, prop.textureValue);
            }
            GUI.DrawTexture(preview_rect_border, Texture2D.whiteTexture, ScaleMode.StretchToFill, false, 0, Color.grey, 3, 5);

            //selection button and pinging
            Rect select_rect = new Rect(preview_rect);

            select_rect.height = 12;
            select_rect.y     += preview_rect.height - 12;
            if (Event.current.commandName == "ObjectSelectorUpdated" && EditorGUIUtility.GetObjectPickerControlID() == texturePickerWindow && texturePickerWindowProperty.name == prop.name)
            {
                prop.textureValue = (Texture)EditorGUIUtility.GetObjectPickerObject();
                ShaderEditor.Repaint();
            }
            if (Event.current.commandName == "ObjectSelectorClosed" && EditorGUIUtility.GetObjectPickerControlID() == texturePickerWindow)
            {
                texturePickerWindow         = -1;
                texturePickerWindowProperty = null;
            }
            if (GUI.Button(select_rect, "Select", EditorStyles.miniButton))
            {
                EditorGUIUtility.ShowObjectPicker <Texture>(prop.textureValue, false, "", 0);
                texturePickerWindow         = EditorGUIUtility.GetObjectPickerControlID();
                texturePickerWindowProperty = prop;
            }
            else if (Event.current.type == EventType.MouseDown && preview_rect.Contains(Event.current.mousePosition))
            {
                EditorGUIUtility.PingObject(prop.textureValue);
            }

            if (!skip_drag_and_drop_handling)
            {
                if ((ShaderEditor.input.is_drag_drop_event) && preview_rect.Contains(ShaderEditor.input.mouse_position) && DragAndDrop.objectReferences[0] is Texture)
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                    if (ShaderEditor.input.is_drop_event)
                    {
                        DragAndDrop.AcceptDrag();
                        prop.textureValue = (Texture)DragAndDrop.objectReferences[0];
                    }
                }
            }

            //scale offset rect

            if (hasFoldoutProperties || DrawingData.currentTexProperty.options.reference_property != null)
            {
                EditorGUI.indentLevel += 2;

                if (DrawingData.currentTexProperty.hasScaleOffset)
                {
                    Rect scale_offset_rect = new Rect(position);
                    scale_offset_rect.y     += 37;
                    scale_offset_rect.width -= 2 + preview_rect.width + 10 + 30;
                    scale_offset_rect.x     += 30;
                    editor.TextureScaleOffsetProperty(scale_offset_rect, prop);
                    if (DrawingData.currentTexProperty.is_animatable)
                    {
                        DrawingData.currentTexProperty.HandleKajAnimatable();
                    }
                }
                float oldLabelWidth = EditorGUIUtility.labelWidth;
                EditorGUIUtility.labelWidth = 128;

                PropertyOptions options = DrawingData.currentTexProperty.options;
                if (options.reference_property != null)
                {
                    ShaderProperty property = ShaderEditor.active.propertyDictionary[options.reference_property];
                    property.Draw(useEditorIndent: true);
                }
                if (options.reference_properties != null)
                {
                    foreach (string r_property in options.reference_properties)
                    {
                        ShaderProperty property = ShaderEditor.active.propertyDictionary[r_property];
                        property.Draw(useEditorIndent: true);
                        if (DrawingData.currentTexProperty.is_animatable)
                        {
                            property.HandleKajAnimatable();
                        }
                    }
                }
                EditorGUIUtility.labelWidth = oldLabelWidth;
                EditorGUI.indentLevel      -= 2;
            }

            Rect label_rect = new Rect(position);

            label_rect.x += 2;
            label_rect.y += 2;
            GUI.Label(label_rect, label);

            GUILayoutUtility.GetRect(0, 5);

            DrawingData.lastGuiObjectRect = border;
        }
        private void DoCommands()
        {
            Event e = Event.current;

            switch (e.type)
            {
            case EventType.KeyDown:
            {
                if (Event.current.keyCode == KeyCode.Delete)
                {
                    if (TreeView.HasFocus())
                    {
                        RemoveAsset();
                    }
                }
                break;
            }
            }

            EditorGUILayout.BeginHorizontal();

            int  selectedRootItemsCount = TreeView.SelectedRootItemsCount;
            bool hasSelectedRootItems   = TreeView.HasSelectedRootItems;

            if (m_folders != null && m_folders.Length == 1)
            {
                if (GUILayout.Button("Add Asset"))
                {
                    PickObject();
                }
            }

            if (m_selectedRootItemsCount == 1)
            {
                if (GUILayout.Button("Rename Asset"))
                {
                    RenameAsset();
                }

                if (GUILayout.Button("Ping Asset"))
                {
                    PingAsset();
                }
            }
            m_selectedRootItemsCount = TreeView.SelectedRootItemsCount;

            if (m_hasSelectedRootItems)
            {
                if (GUILayout.Button("Remove Asset"))
                {
                    RemoveAsset();
                }
            }
            m_hasSelectedRootItems = TreeView.HasSelectedRootItems;

            EditorGUILayout.EndHorizontal();

            if (Event.current.commandName == "ObjectSelectorUpdated" && EditorGUIUtility.GetObjectPickerControlID() == m_currentPickerWindow)
            {
                m_pickedObject = EditorGUIUtility.GetObjectPickerObject();
            }
            else
            {
                if (Event.current.commandName == "ObjectSelectorClosed" && EditorGUIUtility.GetObjectPickerControlID() == m_currentPickerWindow)
                {
                    m_currentPickerWindow = -1;
                    if (m_pickedObject != null)
                    {
                        if (m_folders[0].Assets == null || !m_folders[0].Assets.Any(a => a.Object == m_pickedObject || a.Object != null && a.Object.name == m_pickedObject.name && a.Object.GetType() == m_pickedObject.GetType()))
                        {
                            if (m_pickedObject == null || m_pickedObject.GetType().Assembly.FullName.Contains("UnityEditor"))
                            {
                                EditorUtility.DisplayDialog("Unable to add asset",
                                                            string.Format("Unable to add asset {0} from assembly {1}", m_pickedObject.GetType().Name, m_pickedObject.GetType().Assembly.GetName()), "OK");
                            }
                            else
                            {
                                bool moveToNewLocation = MoveToNewLocationDialog(new[] { m_pickedObject }, m_folders[0]);
                                AddAssetToFolder(new[] { m_pickedObject }, m_folders[0], moveToNewLocation);
                            }
                        }
                        m_pickedObject = null;
                    }
                }
            }
        }
        void DrawRendererListLayout(ReorderableList list, SerializedProperty prop)
        {
            list.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) =>
            {
                rect.y += 2;
                Rect indexRect = new Rect(rect.x, rect.y, 14, EditorGUIUtility.singleLineHeight);
                EditorGUI.LabelField(indexRect, index.ToString());
                Rect objRect = new Rect(rect.x + indexRect.width, rect.y, rect.width - 134, EditorGUIUtility.singleLineHeight);

                EditorGUI.BeginChangeCheck();
                EditorGUI.ObjectField(objRect, prop.GetArrayElementAtIndex(index), GUIContent.none);
                if (EditorGUI.EndChangeCheck())
                {
                    EditorUtility.SetDirty(target);
                }

                Rect defaultButton   = new Rect(rect.width - 90, rect.y, 86, EditorGUIUtility.singleLineHeight);
                var  defaultRenderer = m_DefaultRendererProp.intValue;
                GUI.enabled = index != defaultRenderer;
                if (GUI.Button(defaultButton, !GUI.enabled ? Styles.rendererDefaultText : Styles.rendererSetDefaultText))
                {
                    m_DefaultRendererProp.intValue = index;
                    EditorUtility.SetDirty(target);
                }
                GUI.enabled = true;

                Rect selectRect = new Rect(rect.x + rect.width - 24, rect.y, 24, EditorGUIUtility.singleLineHeight);

                UniversalRenderPipelineAsset asset = target as UniversalRenderPipelineAsset;

                if (asset.ValidateRendererData(index))
                {
                    if (GUI.Button(selectRect, Styles.rendererSettingsText))
                    {
                        Selection.SetActiveObjectWithContext(prop.GetArrayElementAtIndex(index).objectReferenceValue,
                                                             null);
                    }
                }
                else // Missing ScriptableRendererData
                {
                    if (GUI.Button(selectRect, index == defaultRenderer ? Styles.rendererDefaultMissingText : Styles.rendererMissingText))
                    {
                        EditorGUIUtility.ShowObjectPicker <ScriptableRendererData>(null, false, null, index);
                    }
                }

                // If object selector chose an object, assign it to the correct ScriptableRendererData slot.
                if (Event.current.commandName == "ObjectSelectorUpdated" && EditorGUIUtility.GetObjectPickerControlID() == index)
                {
                    prop.GetArrayElementAtIndex(index).objectReferenceValue = EditorGUIUtility.GetObjectPickerObject();
                }
            };

            list.drawHeaderCallback = (Rect rect) =>
            {
                EditorGUI.LabelField(rect, Styles.rendererHeaderText);
                list.index = list.count - 1;
            };

            list.onCanRemoveCallback = li => { return(li.count > 1); };

            list.onRemoveCallback = li =>
            {
                if (li.serializedProperty.arraySize - 1 != m_DefaultRendererProp.intValue)
                {
                    if (li.serializedProperty.GetArrayElementAtIndex(li.serializedProperty.arraySize - 1).objectReferenceValue != null)
                    {
                        li.serializedProperty.DeleteArrayElementAtIndex(li.serializedProperty.arraySize - 1);
                    }
                    li.serializedProperty.arraySize--;
                    li.index = li.count - 1;
                }
                else
                {
                    EditorUtility.DisplayDialog(Styles.rendererListDefaultMessage.text, Styles.rendererListDefaultMessage.tooltip,
                                                "Close");
                }
                EditorUtility.SetDirty(target);
            };
        }
예제 #18
0
        private void OnInspectorGUI_Source()
        {
            // Display the file name and buttons to load new files
            MediaPlayer mediaPlayer = (this.target) as MediaPlayer;

            EditorGUILayout.PropertyField(_propMediaSource);

            if (MediaSource.Reference == (MediaSource)_propMediaSource.enumValueIndex)
            {
                EditorGUILayout.PropertyField(_propMediaReference);
            }

            EditorGUILayout.BeginVertical(GUI.skin.box);

            if (MediaSource.Reference != (MediaSource)_propMediaSource.enumValueIndex)
            {
                OnInspectorGUI_CopyableFilename(mediaPlayer.MediaPath.Path);
                EditorGUILayout.PropertyField(_propMediaPath);
            }

            //if (!Application.isPlaying)
            {
                GUI.color = Color.white;
                GUILayout.BeginHorizontal();

                if (_allowDeveloperMode)
                {
                    if (GUILayout.Button("Rewind"))
                    {
                        mediaPlayer.Rewind(true);
                    }
                    if (GUILayout.Button("Preroll"))
                    {
                        mediaPlayer.RewindPrerollPause();
                    }
                    if (GUILayout.Button("End"))
                    {
                        mediaPlayer.Control.Seek(mediaPlayer.Info.GetDuration());
                    }
                }
                if (GUILayout.Button("Close"))
                {
                    mediaPlayer.CloseMedia();
                }
                if (GUILayout.Button("Load"))
                {
                    if (mediaPlayer.MediaSource == MediaSource.Path)
                    {
                        mediaPlayer.OpenMedia(mediaPlayer.MediaPath.PathType, mediaPlayer.MediaPath.Path, mediaPlayer.AutoStart);
                    }
                    else if (mediaPlayer.MediaSource == MediaSource.Reference)
                    {
                        mediaPlayer.OpenMedia(mediaPlayer.MediaReference, mediaPlayer.AutoStart);
                    }
                }

                /*if (media.Control != null)
                 * {
                 *      if (GUILayout.Button("Unload"))
                 *      {
                 *              media.CloseVideo();
                 *      }
                 * }*/

                if (EditorGUIUtility.GetObjectPickerControlID() == 100 &&
                    Event.current.commandName == "ObjectSelectorClosed")
                {
                    MediaReference mediaRef = (MediaReference)EditorGUIUtility.GetObjectPickerObject();
                    if (mediaRef)
                    {
                        _propMediaSource.enumValueIndex          = (int)MediaSource.Reference;
                        _propMediaReference.objectReferenceValue = mediaRef;
                    }
                }

                GUI.color = Color.green;
                MediaPathDrawer.ShowBrowseButtonIcon(_propMediaPath, _propMediaSource);
                GUI.color = Color.white;

                GUILayout.EndHorizontal();

                //MediaPath mediaPath = new MediaPath(_propMediaPath.FindPropertyRelative("_path").stringValue, (MediaPathType)_propMediaPath.FindPropertyRelative("_pathType").enumValueIndex);
                //ShowFileWarningMessages((MediaSource)_propMediaSource.enumValueIndex, mediaPath, (MediaReference)_propMediaReference.objectReferenceValue, mediaPlayer.AutoOpen, Platform.Unknown);
                GUI.color = Color.white;
            }

            if (MediaSource.Reference != (MediaSource)_propMediaSource.enumValueIndex)
            {
                GUILayout.Label("Fallback Media Hints", EditorStyles.boldLabel);
                EditorGUILayout.PropertyField(_propFallbackMediaHints);
            }

            EditorGUILayout.EndVertical();
        }
    private void DrawLeftDataPanel()
    {
        tabBar = new Rect(2, 60, position.width * resizer.SizeRatio - 3, tabBarHeight);
        GUILayout.BeginArea(tabBar, EditorStyles.helpBox);
        EditorGUILayout.BeginHorizontal();
        int tab = -1;

        tab = GUILayout.Toolbar(CurrentTab, TabTitles);

        if (tab != CurrentTab)
        {
            searchString   = "";
            showRightPanel = false;
            filter         = 0;
            GUI.FocusControl("");
        }

        CurrentTab = tab;

        EditorGUILayout.EndHorizontal();
        GUILayout.EndArea();
        Rect leftDataArea = new Rect(tabBar.x, tabBar.y + tabBar.height, (position.width * resizer.SizeRatio - 3), position.height - 60 - tabBar.height - 3);

        if (CurrentTab == 0)
        {
            leftDataArea.height -= 25;
        }
        GUILayout.BeginArea(leftDataArea, EditorStyles.helpBox);
        using (var v = new EditorGUILayout.VerticalScope())
        {
            using (var scrollView = new EditorGUILayout.ScrollViewScope(leftScroll, GUILayout.Width(leftDataArea.width - 5), GUILayout.Height(leftDataArea.height - 1)))
            {
                leftScroll = scrollView.scrollPosition;

                switch (CurrentTab)
                {
                case 0:
                {
                    DrawLeftSceneSection(leftDataArea);
                }
                break;

                case 1:
                {
                    DrawLeftEventSection(leftDataArea);
                }
                break;

                case 2:
                {
                    DrawLeftListenerSection(leftDataArea);
                }
                break;

                case 3:
                {
                    DrawLeftReferenceSection(leftDataArea);
                }
                break;

                default:
                    break;
                }
            }
        }

        GUILayout.EndArea();

        switch (CurrentTab)
        {
        case 0:
        {
            GUILayout.BeginArea(new Rect(leftDataArea.x, leftDataArea.height + leftDataArea.y + 3, leftDataArea.width, 25));
            if (GUILayout.Button("Add Scene"))
            {
                scenePickerID = EditorGUIUtility.GetControlID(FocusType.Keyboard);

                EditorGUIUtility.ShowObjectPicker <SceneAsset>(null, false, "", scenePickerID);
            }

            if (Event.current.commandName == "ObjectSelectorUpdated" && EditorGUIUtility.GetObjectPickerControlID() == scenePickerID)
            {
                scenePickerID = -1;
            }
            else if (Event.current.commandName == "ObjectSelectorClosed" && EditorGUIUtility.GetObjectPickerControlID() == scenePickerID)
            {
                pickedScene = (SceneAsset)EditorGUIUtility.GetObjectPickerObject();
            }

            GUILayout.EndArea();
        }
        break;

        default:
            break;
        }
    }
예제 #20
0
        //=====================================================================================================================//
        //============================================= Unity Callback Methods ================================================//
        //=====================================================================================================================//

        #region Unity Callback Methods

        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            defaultColor = GUI.color;
            action       = property.FindPropertyRelative("action");
            type         = property.FindPropertyRelative("type");
            behaviour    = property.FindPropertyRelative("behaviour");
            collider     = property.FindPropertyRelative("collider");
            renderer     = property.FindPropertyRelative("renderer");
            cloth        = property.FindPropertyRelative("cloth");
            lodGroup     = property.FindPropertyRelative("lodGroup");
            gameObject   = property.FindPropertyRelative("_gameObject");
            methodName   = property.FindPropertyRelative("_methodName");
            methodIndex  = property.FindPropertyRelative("_methodIdx");
            methodArg    = property.FindPropertyRelative("_methodArg");

            serializedObject = property.serializedObject;

            int indentLevel = EditorGUI.indentLevel;

            EditorGUI.indentLevel = 0;

            EditorGUI.BeginChangeCheck();

            //Draw Action field
            var fieldRect = position;

            fieldRect.x     += 5f;
            fieldRect.width  = 140f;
            fieldRect.y     += EditorGUIUtility.singleLineHeight * 1.25f + 2.5f;
            fieldRect.height = EditorGUIUtility.singleLineHeight;

            if (gameObject.objectReferenceValue == null || (action.enumValueIndex == 2 && (behaviour.objectReferenceValue == null || methodIndex.intValue == -1)))
            {
                GUI.color = Color.red;
            }

            EditorGUI.PropertyField(fieldRect, action, GUIContent.none);

            //Draw Target field
            fieldRect.x    += 145f;
            fieldRect.width = position.width - 155f;
            var     buttonName = "None (Behaviour)";
            Texture texture    = null;

            if (gameObject.objectReferenceValue != null)
            {
                buttonName = gameObject.objectReferenceValue.name + ".";
            }

            SerializedProperty targetProperty = null;

            switch ((BehaviourTarget.BehaviourType)type.enumValueIndex)
            {
            case BehaviourTarget.BehaviourType.Behaviour:
                targetProperty = behaviour;
                break;

            case BehaviourTarget.BehaviourType.Cloth:
                targetProperty = cloth;
                break;

            case BehaviourTarget.BehaviourType.Collider:
                targetProperty = collider;
                break;

            case BehaviourTarget.BehaviourType.LODGroup:
                targetProperty = lodGroup;
                break;

            case BehaviourTarget.BehaviourType.Renderer:
                targetProperty = renderer;
                break;
            }

            if (targetProperty != null && targetProperty.objectReferenceValue != null)
            {
                buttonName += targetProperty.objectReferenceValue.GetType().Name;
                texture     = AssetPreview.GetMiniThumbnail(targetProperty.objectReferenceValue);
            }

            GUI.SetNextControlName("Target Field");
            GUI.Box(fieldRect, new GUIContent(buttonName, texture), GUI.skin.FindStyle("objectField"));

            GUI.color = defaultColor;

            var pickerRect = fieldRect;

            pickerRect.x     = fieldRect.xMax - 15f;
            pickerRect.width = 15f;

            fieldRect.xMax -= 15f;

            var evt = Event.current;

            if (pickerRect.Contains(evt.mousePosition))
            {
                GUI.FocusControl("Target Field");
                switch (evt.type)
                {
                case EventType.MouseDown:
                    if (evt.button == 0)
                    {
                        pickerID = GUIUtility.GetControlID(FocusType.Passive) + 100;
                        var filter = (BehaviourTarget.ActionType)action.enumValueIndex == BehaviourTarget.ActionType.InvokeMethod ? "t:MonoBehaviour": "t:Behaviour t:Collider t:Cloth t:Renderer t:LODGroup";
                        EditorGUIUtility.ShowObjectPicker <GameObject>(null, true, filter, pickerID);
                        evt.Use();
                    }
                    break;
                }
            }
            if (Event.current.type == EventType.Layout)
            {
                if (Event.current.commandName == "ObjectSelectorClosed" && EditorGUIUtility.GetObjectPickerControlID() == pickerID)
                {
                    pickerID = -1;
                    GUI.FocusControl("Target Field");
                    var selectedObj = (GameObject)EditorGUIUtility.GetObjectPickerObject();
                    if (selectedObj != null)
                    {
                        var rect = position;
                        rect.position += fieldRect.position;
                        rect.x        -= fieldRect.width / 4f;
                        rect.y        += fieldRect.height * 1.5f;
                        DisplayBehaviours(evt, selectedObj, rect);
                        Event.current.Use();
                        serializedObject.ApplyModifiedProperties();
                    }
                }
            }
            evt = Event.current;
            if (fieldRect.Contains(evt.mousePosition))
            {
                GUI.FocusControl("Target Field");
                switch (evt.type)
                {
                case EventType.KeyDown:
                    if (evt.keyCode == KeyCode.Delete || evt.keyCode == KeyCode.Backspace)
                    {
                        gameObject.objectReferenceValue = null;
                        GUI.changed = true;
                        serializedObject.ApplyModifiedProperties();
                        evt.Use();
                    }
                    break;

                case EventType.MouseDown:
                    if (evt.button == 0)
                    {
                        if (gameObject.objectReferenceValue != null)
                        {
                            EditorGUIUtility.PingObject(gameObject.objectReferenceValue.GetInstanceID());
                            evt.Use();
                        }
                    }
                    break;

                case EventType.ContextClick:
                    if (gameObject.objectReferenceValue != null)
                    {
                        EditorGUIUtility.PingObject(gameObject.objectReferenceValue.GetInstanceID());
                        DisplayBehaviours(evt, (GameObject)gameObject.objectReferenceValue);
                        evt.Use();
                    }
                    break;

                case EventType.DragUpdated:
                case EventType.DragPerform:
                    DragAndDrop.visualMode = DragAndDropVisualMode.Generic;

                    if (evt.type == EventType.DragPerform && DragAndDrop.objectReferences.Length == 1 && DragAndDrop.objectReferences[0] != null && GUI.enabled)
                    {
                        var _go = (GameObject)DragAndDrop.objectReferences[0];
                        DisplayBehaviours(evt, _go);
                        DragAndDrop.AcceptDrag();
                        evt.Use();
                    }
                    break;
                }
            }

            if ((BehaviourTarget.ActionType)action.enumValueIndex == BehaviourTarget.ActionType.InvokeMethod)
            {
                var methodRect = position;
                methodRect.y      = fieldRect.y + EditorGUIUtility.singleLineHeight + 2.5f;
                methodRect.height = EditorGUIUtility.singleLineHeight;
                methodRect.width  = position.width - 10f;
                ResolveMethods(methodRect);
            }

            //Apply changes
            if (EditorGUI.EndChangeCheck())
            {
                serializedObject.ApplyModifiedProperties();
            }

            EditorGUI.indentLevel = indentLevel;
            GUI.color             = defaultColor;
        }
예제 #21
0
        void OnDrawElement(Rect rect, int index, bool isActive, bool isFocused)
        {
            rect.y += 2;
            Rect indexRect = new Rect(rect.x, rect.y, 14, EditorGUIUtility.singleLineHeight);

            EditorGUI.LabelField(indexRect, index.ToString());
            Rect objRect = new Rect(rect.x + indexRect.width, rect.y, rect.width - 134, EditorGUIUtility.singleLineHeight);

            EditorGUI.BeginChangeCheck();
            EditorGUI.ObjectField(objRect, m_RendererDataProp.GetArrayElementAtIndex(index), GUIContent.none);
            if (EditorGUI.EndChangeCheck())
            {
                EditorUtility.SetDirty(target);
            }

            Rect defaultButton   = new Rect(rect.width - 75, rect.y, 86, EditorGUIUtility.singleLineHeight);
            var  defaultRenderer = m_DefaultRendererProp.intValue;

            GUI.enabled = index != defaultRenderer;
            if (GUI.Button(defaultButton, !GUI.enabled ? Styles.rendererDefaultText : Styles.rendererSetDefaultText))
            {
                m_DefaultRendererProp.intValue = index;
                EditorUtility.SetDirty(target);
            }
            GUI.enabled = true;

            Rect selectRect = new Rect(rect.x + rect.width - 24, rect.y, 24, EditorGUIUtility.singleLineHeight);

            UniversalRenderPipelineAsset asset = target as UniversalRenderPipelineAsset;

            if (asset.ValidateRendererData(index))
            {
                if (GUI.Button(selectRect, Styles.rendererSettingsText))
                {
                    Selection.SetActiveObjectWithContext(m_RendererDataProp.GetArrayElementAtIndex(index).objectReferenceValue,
                                                         null);
                }
            }
            else // Missing ScriptableRendererData
            {
                if (GUI.Button(selectRect, index == defaultRenderer ? Styles.rendererDefaultMissingText : Styles.rendererMissingText))
                {
                    EditorGUIUtility.ShowObjectPicker <ScriptableRendererData>(null, false, null, index);
                }
            }

            // If object selector chose an object, assign it to the correct ScriptableRendererData slot.
            if (Event.current.commandName == "ObjectSelectorUpdated" && EditorGUIUtility.GetObjectPickerControlID() == index)
            {
                m_RendererDataProp.GetArrayElementAtIndex(index).objectReferenceValue = EditorGUIUtility.GetObjectPickerObject();
            }
        }
예제 #22
0
 private void _setPickerObj(bool checkMulti = false)
 {
     if (mSelectingIndex >= 0 && mSelectingIndex < mTarget.UIArray.Count)
     {
         GameObject obj = EditorGUIUtility.GetObjectPickerObject() as GameObject;
         if (null != obj)
         {
             if (checkMulti)
             {
                 UIBehaviour[] uIBehaviours = obj.GetComponents <UIBehaviour>();
                 if (uIBehaviours.Length > 0)
                 {
                     if (uIBehaviours.Length > 1)
                     {
                         List <UIBehaviour> list    = new List <UIBehaviour>();
                         List <string>      options = new List <string>();
                         for (int i = 0; i < uIBehaviours.Length; i++)
                         {
                             UIBehaviour ui = uIBehaviours[i];
                             if (!mTarget.UIArray.Contains(ui) || mTarget.UIArray.IndexOf(ui) == mSelectingIndex)
                             {
                                 list.Add(ui);
                                 options.Add(ui.ToString());
                             }
                         }
                         if (list.Count > 1)
                         {
                             //TODO:显示选择窗口
                             SelectWindow.ShowWithOptions(options.ToArray(), (int index) =>
                             {
                                 //Debug.Log("Selceted:" + index + ",mTarget.UIArray.Count:" + mTarget.UIArray.Count + "ui index:" + mSelectingIndex);
                                 if (-1 == index)
                                 {
                                     mTarget.UIArray.RemoveAt(mSelectingIndex);
                                 }
                                 else
                                 {
                                     mTarget.UIArray[mSelectingIndex] = list[index];
                                 }
                             });
                         }
                         if (list.Count == 1)
                         {
                             mTarget.UIArray[mSelectingIndex] = list[0];
                         }
                     }
                     else
                     {
                         mTarget.UIArray[mSelectingIndex] = uIBehaviours[0];
                     }
                 }
             }
             else
             {
                 EditorGUIUtility.PingObject(obj);
                 mTarget.UIArray[mSelectingIndex] = obj.GetComponent <UIBehaviour>();
             }
         }
         else
         {
             mTarget.UIArray[mSelectingIndex] = null;
         }
     }
 }
예제 #23
0
        void DrawButtonSection()
        {
            if (targets.Length > 1)
            {
                return;
            }

            SerializedProperty clipsProperty = serializedObject.FindProperty("_audioClips");

            if (Event.current.commandName == "ObjectSelectorClosed" && _pickedObjectReady)
            {
                _pickedObjectReady = false;
                if (EditorGUIUtility.GetObjectPickerObject() != null)
                {
                    if (clipsProperty.arraySize == 0 || clipsProperty.GetArrayElementAtIndex(clipsProperty.arraySize - 1).objectReferenceValue != null)
                    {
                        clipsProperty.arraySize++;
                    }

                    clipsProperty.GetArrayElementAtIndex(clipsProperty.arraySize - 1).objectReferenceValue = EditorGUIUtility.GetObjectPickerObject();
                    serializedObject.ApplyModifiedProperties();
                }
            }

            GUILayout.BeginHorizontal();

            if (clipsProperty != null)
            {
                if (GUILayout.Button("Add Clip", GUILayout.MaxWidth(80)))
                {
                    UnityEngine.Object defaultClip = null;

                    if (clipsProperty.arraySize > 0)
                    {
                        defaultClip = clipsProperty.GetArrayElementAtIndex(clipsProperty.arraySize - 1).objectReferenceValue;
                    }

                    _pickedObjectReady = true;
                    EditorGUIUtility.ShowObjectPicker <AudioClip>(defaultClip, false, "", -1);
                }

                if (GUILayout.Button("Clear Clips", GUILayout.MaxWidth(80)))
                {
                    clipsProperty.arraySize = 0;
                    serializedObject.ApplyModifiedProperties();
                }
            }

            if (_bank is BlendSoundBank)
            {
                EditorGUIUtility.labelWidth = 45f;
                _blendParameter             = EditorGUILayout.Slider(new GUIContent("Blend"), _blendParameter, 0, 1);
            }
            else if (_bank is SequenceSoundBank)
            {
                SequenceSoundInstance sequence = null;
                if (_lastInstance != null)
                {
                    sequence = _lastInstance as SequenceSoundInstance;
                }

                if (sequence != null && sequence.HasPreviousSection)
                {
                    if (GUILayout.Button("<<", GUILayout.MaxWidth(50f)))
                    {
                        sequence.PlayPreviousSection();
                    }
                }
                else
                {
                    EditorGUI.BeginDisabledGroup(true);
                    GUILayout.Button("<<", GUILayout.MaxWidth(50f));
                    EditorGUI.EndDisabledGroup();
                }

                if (sequence != null && sequence.HasNextSection)
                {
                    if (GUILayout.Button(">>", GUILayout.MaxWidth(50f)))
                    {
                        sequence.PlayNextSection();
                    }
                }
                else
                {
                    EditorGUI.BeginDisabledGroup(true);
                    GUILayout.Button(">>", GUILayout.MaxWidth(50f));
                    EditorGUI.EndDisabledGroup();
                }

                GUILayout.FlexibleSpace();
            }
            else
            {
                GUILayout.FlexibleSpace();
            }

            if (GUILayout.Button("PLAY", GUILayout.MaxWidth(80f)))
            {
                if (_soundPool == null)
                {
                    _soundPool = new EditorSoundPool();
                    Selection.selectionChanged += _soundPool.Clear;
                }
                else
                {
                    _soundPool.Clear();
                }

                _lastInstance = _bank.TestInEditor(_soundPool);
            }

            if (GUILayout.Button("STOP", GUILayout.MaxWidth(80f)))
            {
                if (_lastInstance != null)
                {
                    _lastInstance.StopAndDestroy();
                }
            }

            BlendSoundInstance blend = _lastInstance as BlendSoundInstance;

            if (blend != null)
            {
                blend.SetBlendParameter(_blendParameter);
            }

            GUILayout.EndHorizontal();
        }
예제 #24
0
        // Drop area for Backwards Compatible Races
        private void CompatibleRacesDropArea(Rect dropArea, SerializedProperty crossCompatibilitySettingsData)
        {
            Event evt = Event.current;

            //make the box clickable so that the user can select raceData assets from the asset selection window
            if (evt.type == EventType.MouseUp)
            {
                if (dropArea.Contains(evt.mousePosition))
                {
                    compatibleRacePickerID = EditorGUIUtility.GetControlID(new GUIContent("crfObjectPicker"), FocusType.Passive);
                    EditorGUIUtility.ShowObjectPicker <RaceData>(null, false, "", compatibleRacePickerID);
                    Event.current.Use();                    //stops the Mismatched LayoutGroup errors
                    return;
                }
            }
            if (evt.commandName == "ObjectSelectorUpdated" && EditorGUIUtility.GetObjectPickerControlID() == compatibleRacePickerID)
            {
                RaceData tempRaceDataAsset = EditorGUIUtility.GetObjectPickerObject() as RaceData;
                if (tempRaceDataAsset)
                {
                    AddRaceDataAsset(tempRaceDataAsset, crossCompatibilitySettingsData);
                }
                if (Event.current.type != EventType.Layout)
                {
                    Event.current.Use();                    //stops the Mismatched LayoutGroup errors
                }
                return;
            }
            if (evt.type == EventType.DragUpdated)
            {
                if (dropArea.Contains(evt.mousePosition))
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                }
            }
            if (evt.type == EventType.DragPerform)
            {
                if (dropArea.Contains(evt.mousePosition))
                {
                    DragAndDrop.AcceptDrag();

                    UnityEngine.Object[] draggedObjects = DragAndDrop.objectReferences as UnityEngine.Object[];
                    for (int i = 0; i < draggedObjects.Length; i++)
                    {
                        if (draggedObjects[i])
                        {
                            RaceData tempRaceDataAsset = draggedObjects[i] as RaceData;
                            if (tempRaceDataAsset)
                            {
                                AddRaceDataAsset(tempRaceDataAsset, crossCompatibilitySettingsData);
                                continue;
                            }

                            var path = AssetDatabase.GetAssetPath(draggedObjects[i]);
                            if (System.IO.Directory.Exists(path))
                            {
                                RecursiveScanFoldersForAssets(path, crossCompatibilitySettingsData);
                            }
                        }
                    }
                }
            }
        }
예제 #25
0
    private bool FramePreviewButton(LZFighterFrame frame, bool selected, int frameID)
    {
        Rect  rect      = GUILayoutUtility.GetRect(GUIContent.none, GUITools.NodeStyle, GUILayout.Height(75), GUILayout.Width(75));
        bool  clicked   = false;
        Event ev        = Event.current;
        int   controlID = GUIUtility.GetControlID(FocusType.Passive);

        GUITools.ButtonInfo info = GUIUtility.GetStateObject(typeof(GUITools.ButtonInfo), controlID) as GUITools.ButtonInfo;

        switch (ev.GetTypeForControl(controlID))
        {
        case EventType.MouseUp:
            info.mouseDown = false;
            if (rect.Contains(ev.mousePosition))
            {
                clicked = true;
            }
            if (GUIUtility.hotControl == controlID)
            {
                ev.Use();
                GUIUtility.hotControl = 0;
            }
            break;

        case EventType.MouseDown:
            if (rect.Contains(ev.mousePosition))
            {
                info.mouseDown = true;
                ev.Use();
                GUIUtility.hotControl = controlID;
                if (ev.clickCount == 2)
                {
                    EditorGUIUtility.ShowObjectPicker <Sprite>(frame.sprite, false, "", controlID);
                }
            }
            break;

        case EventType.ExecuteCommand:
            if (ev.commandName == "ObjectSelectorUpdated" && selectedFrame == frameID)
            {
                frame.sprite = (Sprite)EditorGUIUtility.GetObjectPickerObject();
                ev.Use();
            }
            break;

        case EventType.Repaint:
            Color rectangle = new Color(0.6f, 0.6f, 0.6f);
            if (selected)
            {
                rectangle = GUITools.darkCyan;
            }
            else if (info.mouseDown)
            {
                rectangle = Color.gray;
            }
            rect = GUITools.PaddedContainer.padding.Remove(rect);
            EditorGUI.DrawRect(rect, rectangle);

            if (frame.sprite != null)
            {
                GUI.DrawTextureWithTexCoords(rect, frame.sprite.texture, frame.sprite.GetSpriteRect());
            }
            break;
        }

        return(clicked);
    }
예제 #26
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            EditorGUI.BeginProperty(position, label, property);

            var textProperty     = property.FindPropertyRelative("text");
            var filenameProperty = property.FindPropertyRelative("filename");
            var typeProperty     = property.FindPropertyRelative("type");

            float y      = position.y;
            float x      = position.x;
            float height = GetPropertyHeight(property, label);
            float width  = position.width - HORIZONTAL_GAP * 2;

            Rect nameRect  = new Rect(x, y, Mathf.Min(80, width * 0.3f), height);
            Rect typeRect  = new Rect(nameRect.xMax + HORIZONTAL_GAP, y, Mathf.Min(100, width * 0.2f), height);
            Rect valueRect = new Rect(typeRect.xMax + HORIZONTAL_GAP, y, 0, height);

            EditorGUI.LabelField(nameRect, property.displayName);

            LuaScriptBindEnum typeValue = (LuaScriptBindEnum)typeProperty.enumValueIndex;

            EditorGUI.BeginChangeCheck();
            typeValue = (LuaScriptBindEnum)EditorGUI.EnumPopup(typeRect, typeValue);
            if (EditorGUI.EndChangeCheck())
            {
                typeProperty.enumValueIndex = (int)typeValue;
            }

            switch (typeValue)
            {
            case LuaScriptBindEnum.TextAsset:
                valueRect.width = position.xMax - typeRect.xMax - HORIZONTAL_GAP;
                textProperty.objectReferenceValue = EditorGUI.ObjectField(valueRect, GUIContent.none, textProperty.objectReferenceValue, typeof(UnityEngine.TextAsset), false);
                break;

            case LuaScriptBindEnum.Filename:
                valueRect.width = position.xMax - typeRect.xMax - HORIZONTAL_GAP - height;
                if (EditorUtility.IsFieldClick(valueRect, Event.current))
                {
                    var path = string.IsNullOrEmpty(filenameProperty.stringValue) ? "" : FindFilePath(filenameProperty.stringValue.Replace('.', '/'));
                    if (!string.IsNullOrEmpty(path))
                    {
                        Log.Debug(path);
                        EditorUtility.PingObject(path);
                    }
                }
                // var obj = GetDragObject<Object>(valueRect, Event.current);
                if (GUI.Button(new Rect(valueRect.xMax, y, height, height), GUIContent.none, "IN ObjectField"))
                {
                    EditorGUIUtility.ShowObjectPicker <Object>(null, false, property.serializedObject.targetObject.name, 1001);
                }
                if (EditorGUIUtility.GetObjectPickerControlID() == 1001)
                {
                    var obj = EditorGUIUtility.GetObjectPickerObject();
                    if (obj != null)
                    {
                        var path = AssetDatabase.GetAssetPath(obj.GetInstanceID());
                        if (Utility.Path.IsExtension(path, GameConst.LUA_EXTENSIONS.Split(',')))
                        {
                            var start = GameConst.LUA_SCRIPTS_PATH;
                            int idx   = path.IndexOf(start);
                            if (idx == -1)
                            {
                                start = "Resources/";
                                idx   = path.IndexOf(start);
                            }
                            if (idx != -1)
                            {
                                idx += start.Length;
                                path = path.Substring(idx, path.IndexOf(".lua") - idx).Replace('/', '.');
                                // Debug.Log(path);
                                filenameProperty.stringValue = path;
                            }
                        }
                    }
                }
                filenameProperty.stringValue = EditorGUI.TextField(valueRect, GUIContent.none, filenameProperty.stringValue);
                break;
            }
            EditorGUI.EndProperty();
        }
예제 #27
0
        void DrawAtlasSel()
        {
            ImageEx imageEx = target as ImageEx;

            bool grey = EditorGUILayout.Toggle("变灰", imageEx.m_grey);

            if (grey != imageEx.m_grey)
            {
                imageEx.SetGrey(grey);
            }

            string[] ns = UnityEditor.Sprites.Packer.atlasNames;
            if (ns.Length == 0)
            {
                return;
            }
            List <string> l = new List <string>(ns);

            l.Add("CCMJ");
            l.Add("Common");
            l.Add("DDZ");
            l.Add("Main");
            ns = l.ToArray();

            //图集选择
            string curAtlas = EditorPrefs.GetString("cur_atlas");

            using (new AutoBeginHorizontal())
            {
                EditorGUILayout.PrefixLabel("图片选择:");

                int i = Array.IndexOf(ns, curAtlas);
                i = EditorGUILayout.Popup(i, ns);
                if (i != -1 && ns[i] != curAtlas)
                {
                    EditorPrefs.SetString("cur_atlas", ns[i]);
                    curAtlas = ns[i];
                }
                else if (i == -1)
                {
                    curAtlas = string.Empty;
                }

                //图片选择
                if (string.IsNullOrEmpty(curAtlas))
                {
                    return;
                }
                if (GUILayout.Button("图片", EditorStyles.popup, GUILayout.Width(50)))
                {
                    //ImageSelector.Show(curAtlas, OnSel);
                    EditorGUIUtility.ShowObjectPicker <Sprite>(imageEx.sprite, false, "ui_" + curAtlas, 0);;
                    UnityEditor.EditorPrefs.SetString("cur_sprite_picker", "imageex");
                }
                if (Event.current.GetTypeForControl(0) == EventType.ExecuteCommand && Event.current.commandName == "ObjectSelectorUpdated" && UnityEditor.EditorPrefs.GetString("cur_sprite_picker") == "imageex")
                {
                    Sprite s = EditorGUIUtility.GetObjectPickerObject() as Sprite;
                    if (s != null && s != imageEx.sprite)
                    {
                        UnityEditor.Undo.RecordObject(imageEx, "imageEx select");
                        imageEx.sprite = s;
                        if (imageEx.type == Image.Type.Simple)
                        {
                            RectTransform t = imageEx.GetComponent <RectTransform>();
                            if (t.sizeDelta.x == 100 && t.sizeDelta.y == 100)//没有设置过大小的情况下设置成图片大小
                            {
                                t.sizeDelta = s.rect.size;
                            }
                        }
                        UnityEditor.EditorUtility.SetDirty(imageEx);
                    }
                }
            }
        }
예제 #28
0
    /// <summary>
    /// Raises the GU event.
    /// </summary>
    void OnGUI()
    {
        GUI.skin = null;

        if (EditorApplication.isPlaying == false)
        {
            GUILayout.Space(5);

            EditorGUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            GUI.skin = myState == MyStates.Pointer ? null : tilesGuiSkin;
            if (GUILayout.Button(contents.pointer) == true)
            {
                myState = MyStates.Pointer;
                UpdateTemp();
                tileIdx        = -1;
                environmentIdx = -1;
            }
            GUI.skin = null;
            GUILayout.FlexibleSpace();
            EditorGUILayout.EndHorizontal();

            GUILayout.Space(20);

            if (GUILayout.Button("Choose background") == true)
            {
                ShowPicker <Sprite>(PickerState.Map, mapSpriteLabel);
            }

            GUI.skin = tilesGuiSkin;

            GUILayout.Space(5);
            EditorGUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            GUILayout.Label("------------Environment------------");
            GUILayout.FlexibleSpace();
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.PrefixLabel("In game sorting");
            inGameSorting = EditorGUILayout.Toggle(inGameSorting);
            EditorGUILayout.EndHorizontal();

            environmentScrollPos = EditorGUILayout.BeginScrollView(environmentScrollPos, GUILayout.MaxHeight(120));
            int environmentNewIdx = GUILayout.SelectionGrid(environmentIdx, environmentTextures, 4);
            if (environmentNewIdx != environmentIdx)
            {
                environmentIdx = environmentNewIdx;
                if (environmentIdx >= 0)
                {
                    myState = MyStates.EnvironmentPlacement;
                    UpdateTemp();
                    tileIdx = -1;
                    SetEnvironment(environmentPrefabs[environmentIdx]);
                }
            }
            EditorGUILayout.EndScrollView();

            GUILayout.Space(5);
            EditorGUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            GUILayout.Label("---------------Tiles---------------");
            GUILayout.FlexibleSpace();
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.PrefixLabel("Snap step");
            snapStep = EditorGUILayout.FloatField(snapStep);
            EditorGUILayout.EndHorizontal();

            tilesScrollPos = EditorGUILayout.BeginScrollView(tilesScrollPos, GUILayout.MaxHeight(140));
            int tileNewIdx = GUILayout.SelectionGrid(tileIdx, tileTextures, 4);
            if (tileNewIdx != tileIdx)
            {
                tileIdx = tileNewIdx;
                if (tileIdx >= 0)
                {
                    myState = MyStates.TilePlacement;
                    UpdateTemp();
                    environmentIdx = -1;
                    SetTile(tilePrefabs[tileIdx]);
                }
            }
            EditorGUILayout.EndScrollView();

            GUI.skin = null;

            EditorGUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            if (GUILayout.Button(contents.rotateLeft) == true)
            {
                RotateTile(90f);
            }
            GUILayout.FlexibleSpace();
            if (GUILayout.Button(contents.rotateRight) == true)
            {
                RotateTile(-90f);
            }
            GUILayout.FlexibleSpace();
            EditorGUILayout.EndHorizontal();

            if (myState == MyStates.Pointer)
            {
                GUILayout.Space(20);
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.PrefixLabel("Map name");
                mapName = EditorGUILayout.TextField(mapName);
                EditorGUILayout.EndHorizontal();

                if (GUILayout.Button("Save map") == true)
                {
                    if (mapFolderInspector != null)
                    {
                        if (mapFolderInspector.map != null)
                        {
                            mapFolderInspector.map.gameObject.name = mapName;
                            GameObject newMapPrefab = PrefabUtility.CreatePrefab("Assets/TD2D/Prefabs/Map/LevelMaps/" + mapName + ".prefab", mapFolderInspector.map.gameObject, ReplacePrefabOptions.ConnectToPrefab);
                            AssetDatabase.Refresh();
                            Selection.activeObject = newMapPrefab;
                            EditorUtility.FocusProjectWindow();
                        }
                    }
                }
            }

            // New object selected in picker window
            if (Event.current.commandName == "ObjectSelectorUpdated" && EditorGUIUtility.GetObjectPickerControlID() == currentPickerWindow)
            {
                pickedObject = EditorGUIUtility.GetObjectPickerObject();
            }
            // Picker window closed
            if (Event.current.commandName == "ObjectSelectorClosed" && EditorGUIUtility.GetObjectPickerControlID() == currentPickerWindow)
            {
                switch (pickerState)
                {
                case PickerState.Map:
                    if (pickedObject != null && pickedObject is Sprite && mapFolderInspector != null)
                    {
                        mapFolderInspector.ChangeMapSprite(pickedObject as Sprite);
                        EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene());
                    }
                    break;
                }

                pickedObject = null;
                pickerState  = PickerState.None;
            }
        }
        else
        {
            EditorGUILayout.HelpBox("Editor disabled in play mode", MessageType.Info);
        }
    }
예제 #29
0
    void OnGUI()
    {
        int  i;
        bool shouldRepaint = false;

        //*************************************************************
        //******************* Zoom slider *****************************
        GUILayout.Space(10f);
        EditorGUIUtility.labelWidth = 55f;

        int samplesPerPixel = _samplesPerPixel;

        _samplesPerPixel = EditorGUILayout.IntSlider("Zoom: ", _samplesPerPixel, 2, 1000);

        if (samplesPerPixel != _samplesPerPixel)
        {
            UpdateZoom();
        }

        //*************************************************************
        //******************* ScrollView  *****************************
        Vector2 prevScroll = _scrollPos;

        _scrollPos = GUI.BeginScrollView(new Rect(0f, 0f, this.position.width, this.position.height), _scrollPos, new Rect(0, 0, _scrollViewWidth, 200f));

        if (prevScroll != _scrollPos)
        {
            shouldRepaint = true;
        }

        //*************************************************************
        //******************* Mouse Events ****************************
        if (Event.current.isMouse)
        {
            EventType eventType = Event.current.type;

            Vector2 mousePos = Event.current.mousePosition;

            if (eventType == EventType.MouseDown)
            {
                _draggedHandle = null;
                foreach (EnvelopeHandle handle in _handles)
                {
                    if (handle.HitTest(mousePos))
                    {
                        _draggedHandle = handle;
                        break;
                    }
                }

                if (_draggedHandle == null && _posHandle.HitTest(mousePos))
                {
                    _draggedHandle = _posHandle;
                }
            }
            else if (eventType == EventType.MouseUp)
            {
                _draggedHandle = null;
            }
            else if (eventType == EventType.MouseDrag && _draggedHandle != null)
            {
                if (_draggedHandle.Control == ControlType.Position)
                {
                    int posInSamples = _draggedHandle.EvaluatePosInSamples(mousePos.x);
                    int halfLength   = _envelopeModule.Length / 2;

                    if (posInSamples - halfLength < 0)
                    {
                        posInSamples = halfLength;
                    }
                    else if (posInSamples + halfLength > EnvelopeHandle.MaxSamples)
                    {
                        posInSamples = EnvelopeHandle.MaxSamples - halfLength;
                    }

                    _handles[0].PosInSamples = posInSamples - halfLength;
                    _handles[1].PosInSamples = _handles[0].PosInSamples + _envelopeModule.FadeIn;

                    _handles[3].PosInSamples = posInSamples + halfLength;
                    _handles[2].PosInSamples = _handles[3].PosInSamples - _envelopeModule.FadeOut;

                    _posHandle.PosInSamples = posInSamples;

                    _envelopeModule.Offset = _handles[0].PosInSamples;
                }
                else
                {
                    _draggedHandle.Drag(mousePos.x);

                    if (_draggedHandle.Control == ControlType.AttackStart)
                    {
                        _envelopeModule.Offset = _draggedHandle.PosInSamples;
                        _envelopeModule.FadeIn = _handles[1].PosInSamples - _handles[0].PosInSamples;
                        _envelopeModule.Length = _handles[3].PosInSamples - _handles[0].PosInSamples;
                        UpdatePosHandle();
                    }
                    else if (_draggedHandle.Control == ControlType.AttackEnd)
                    {
                        _envelopeModule.FadeIn = _handles[1].PosInSamples - _handles[0].PosInSamples;
                    }
                    else if (_draggedHandle.Control == ControlType.ReleaseStart)
                    {
                        _envelopeModule.FadeOut = _handles[3].PosInSamples - _handles[2].PosInSamples;
                    }
                    else                     //ReleaseEnd
                    {
                        _envelopeModule.FadeOut = _handles[3].PosInSamples - _handles[2].PosInSamples;
                        _envelopeModule.Length  = _handles[3].PosInSamples - _handles[0].PosInSamples;
                        UpdatePosHandle();
                    }
                }

                shouldRepaint = true;
            }
        }

        //*************************************************************
        //******************* Drawing *********************************
        for (i = 0; i < 4; i++)
        {
            _handles[i].DrawHandle();
        }

        _posHandle.DrawHandle();

        for (i = 0; i < 4; i++)
        {
            _linePoints[i] = _handles[i].Position;
        }

        Handles.color = Color.blue;
        Handles.DrawAAPolyLine(2f, _linePoints);
        Handles.color = Color.grey;
        Handles.DrawLine(_start, _end);

        GUI.EndScrollView();

        GUILayout.Space(110f);

        //*************************************************************
        //******************* Info ************************************
        _durationUnit = ( DurationUnit )EditorGUILayout.EnumPopup(_durationUnit, GUILayout.Width(60f));
        GUILayoutOption labelWidth = GUILayout.Width(90f);

        GUILayout.BeginHorizontal();
        GUILayout.Label("Length: " + GetLengthStringForSamples(_envelopeModule.Length), labelWidth);
        GUILayout.Label("Offset: " + GetLengthStringForSamples(_envelopeModule.Offset), labelWidth);
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        GUILayout.Label("Fade In: " + GetLengthStringForSamples(_envelopeModule.FadeIn), labelWidth);
        GUILayout.Label("Fade Out: " + GetLengthStringForSamples(_envelopeModule.FadeOut), labelWidth);
        GUILayout.EndHorizontal();

        GUILayout.Space(10f);
        _envelopeModule.Pulse = ( PulseModule )EditorGUILayout.ObjectField(_envelopeModule.Pulse, typeof(PulseModule), true, GUILayout.Width(130f));

        GUI.enabled = _envelopeModule.Pulse != null;

        _envelopeModule.MapLengthToPulse = GUILayout.Toggle(_envelopeModule.MapLengthToPulse, "Map Length To Pulse", GUILayout.ExpandWidth(false));

        GUI.enabled = true;
        if (_envelopeModule.Pulse != null && _envelopeModule.MapLengthToPulse)
        {
            GUILayout.Label("Length to Pulse ratio: " + _envelopeModule.LengthToPulseRatio.ToString("0.00"));
            _envelopeModule.LengthToPulseRatio = GUILayout.HorizontalSlider(_envelopeModule.LengthToPulseRatio, .1f, 8f, GUILayout.Width(190f));
        }

        //************************************************************************************
        //*********************** ObjectPicker Messages Handling *****************************

        if (Event.current.commandName == "ObjectSelectorUpdated")
        {
            GATSoundBank bank = EditorGUIUtility.GetObjectPickerObject() as GATSoundBank;

            if (bank != null)
            {
                _selectedBankMax = bank.SizeOfLongestSample();
                _selectedBankMin = bank.SizeOfShortestSample();

                shouldRepaint = true;
                _selectedBank = bank;
            }
        }

        //************************************************************************************
        //*********************** SoundBank Clamping *****************************
        GUILayout.BeginArea(new Rect(200f, 130f, 200f, 150f));
        GUILayout.Label("Max Length: " + GetLengthStringForSamples(EnvelopeHandle.MaxSamples));

        EditorGUIUtility.labelWidth = 70f;
        _selectedBank = ( GATSoundBank )EditorGUILayout.ObjectField("SoundBank:", _selectedBank, typeof(GATSoundBank), false);

        if (_selectedBank != null)
        {
            if (GUILayout.Button("Shortest sample:" + GetLengthStringForSamples(_selectedBankMin), GUILayout.Width(140f)))
            {
                EnvelopeHandle.MaxSamples = _selectedBankMin;
                UpdateZoom();
            }

            if (GUILayout.Button("Longest sample:" + GetLengthStringForSamples(_selectedBankMax), GUILayout.Width(140f)))
            {
                EnvelopeHandle.MaxSamples = _selectedBankMax;
                UpdateZoom();
            }
        }
        else
        {
            EditorGUILayout.HelpBox("Select a sound bank to easily map this envelope's max length to the bank's shortest or longest sample.", MessageType.Info);
        }

        //************************************************************************************
        //*********************** Reverse and Normalize **************************************

        _envelopeModule.Reverse = GUILayout.Toggle(_envelopeModule.Reverse, "Reverse");
        GUILayout.BeginHorizontal();
        _envelopeModule.Normalize = GUILayout.Toggle(_envelopeModule.Normalize, "Normalize", GUILayout.Width(75f));
        if (_envelopeModule.Normalize)
        {
            GUILayout.Label(_envelopeModule.NormalizeValue.ToString("0.00"));
            GUILayout.EndHorizontal();
            _envelopeModule.NormalizeValue = GUILayout.HorizontalSlider(_envelopeModule.NormalizeValue, 0f, 1f);
        }
        else
        {
            GUILayout.EndHorizontal();
        }


        GUILayout.EndArea();

        if (shouldRepaint)
        {
            Repaint();
        }
    }
예제 #30
0
        public override void OnInspectorGUI()
        {
            if (folderLoaded)
            {
                EditorTools.Message_static("Loading Complete", "Loaded " + modelCount.ToString() + " models from 'Assets/" + folderString + ".");
                folderLoaded    = false;
                folderString    = "";
                filePathsToLoad = null;
            }

            DrawDefaultInspector();

            if (tools.Button("Load Folder"))
            {
                if (tools.Message("Load Baked Animation In Folder", "Select one of the models in the folder you wish to load.", "OK", "Cancel"))
                {
                    EditorGUIUtility.ShowObjectPicker <GameObject>(null, false, "", objectPickerID);
                }
                GUIUtility.ExitGUI();
            }

            Event currentEvent = Event.current;

            if (currentEvent.type == EventType.ExecuteCommand || currentEvent.type == EventType.ValidateCommand)
            {
                if (currentEvent.commandName == "ObjectSelectorClosed")
                {
                    if (EditorGUIUtility.GetObjectPickerControlID() == objectPickerID)
                    {
                        Object pickedObject = EditorGUIUtility.GetObjectPickerObject();

                        if (pickedObject != null)
                        {
                            folderString = AssetDatabase.GetAssetPath(pickedObject);
                            folderString = folderString.Replace(Path.GetFileName(folderString), "");
                            folderString = folderString.Replace("Assets/", "");

                            filePathsToLoad = Directory.GetFiles(Application.dataPath + "/" + folderString);

                            bool replaceExisting = tools.Message("Load Folder", "Replace any existing models?", "Yes", "No");

                            tools.StartEdit(animator, "Mesh Animator Loaded models");

                            if (replaceExisting)
                            {
                                animator.models.Clear();
                            }

                            modelCount = animator.LoadFromFolder(filePathsToLoad, folderString);

                            tools.EndEdit(animator);

                            folderLoaded = true;

                            GUIUtility.ExitGUI();
                        }
                    }
                }
            }

            if (animator.paused)
            {
                if (tools.Button("Play"))
                {
                    animator.Play();
                }
            }
            else
            {
                if (tools.Button("Pause"))
                {
                    animator.Pause();
                }
            }
        }