Exemplo n.º 1
0
        public override void OnInspectorGUI()
        {
            serializedObject.Update();
            _bot.UpdateGizmosUI(_upToDate);

            // draw script gui
            GUI.enabled = false;
            EditorGUILayout.ObjectField("Script", MonoScript.FromMonoBehaviour((Bot)target), typeof(Bot), false);
            GUI.enabled = true;

            //draw foldout
            _foldout = EditorGUILayout.Foldout(_foldout, "Behaviour Settings");
            EditorPrefs.SetBool("foldout", _foldout);
            serializedObject.Update();
            if (_foldout)
            {
                DrawImage();
                ListLoading();

                if (GUILayout.Button("Randomise Probabilities"))
                {
                    foreach (var action in _bot.reflectionActions)
                    {
                        var actionProperty      = serializedObject.FindProperty(action.name);
                        var probabilityProperty = actionProperty.FindPropertyRelative("probability");
                        probabilityProperty.floatValue = UnityEngine.Random.value;
                    }
                }

                GUILayout.BeginHorizontal();
                if (!_upToDate && GUILayout.Button("Save Preset"))
                {
                    _bot.SavePreset();
                }
                if (!_upToDate && GUILayout.Button("Revert changes"))
                {
                    _bot.UpdatePreset();
                }
                if (_upToDate && GUILayout.Button("Update all other"))
                {
                    _bot.UpdateAllOthers();
                }
                GUILayout.EndHorizontal();
            }

            _generalSettings = EditorGUILayout.Foldout(_generalSettings, "General Settings");
            EditorPrefs.SetBool("general", _generalSettings);
            if (_generalSettings)
            {
                foreach (var name in _bot.reflectionFields)
                {
                    try
                    {
                        EditorGUILayout.PropertyField(serializedObject.FindProperty(name), true);
                    }
                    catch (NullReferenceException)
                    {
                        continue;
                    }
                }
            }

            serializedObject.ApplyModifiedProperties();
        }
Exemplo n.º 2
0
    public override void OnInspectorGUI()
    {
        GUI.enabled = false;
        EditorGUILayout.ObjectField("Script", MonoScript.FromMonoBehaviour((MonoBehaviour)target), typeof(MonoScript), false);
        GUI.enabled = true;

        System.Object old_object = state_machine_property.objectReferenceValue;
        state_machine_property.objectReferenceValue = EditorGUILayout.ObjectField(new GUIContent("State Machine"), state_machine_property.objectReferenceValue, typeof(StateMachine), false);

        if (!ReferenceEquals(state_machine_property.objectReferenceValue, old_object) && state_machine_property.objectReferenceValue != null)
        {
            ClearThenUpdateAttachments();
        }

        if (state_machine_property.objectReferenceValue != null)
        {
            SerializedProperty parameters_property    = new SerializedObject(state_machine_property.objectReferenceValue).FindProperty("parameters");
            SerializedProperty callback_list_property = serialized_target.FindProperty("parameter_callback_list");

            if (callback_list_property.arraySize != parameters_property.arraySize)
            {
                callback_list_property.ClearArray();
                for (int i = 0; i < parameters_property.arraySize; i++)
                {
                    callback_list_property.InsertArrayElementAtIndex(i);
                }
            }

            parameters_foldout = EditorGUILayout.Foldout(parameters_foldout, "Parameters");
            if (parameters_foldout)
            {
                EditorGUI.indentLevel += 1;
                for (int i = 0; i < callback_list_property.arraySize; i++)
                {
                    SerializedProperty array_element  = callback_list_property.GetArrayElementAtIndex(i);
                    string             parameter_name = parameters_property.GetArrayElementAtIndex(i).FindPropertyRelative("_name").stringValue;
                    SerializedProperty index          = array_element.FindPropertyRelative("callback_index");

                    index.intValue = EditorGUILayout.Popup(parameter_name, index.intValue, parameter_candidate_names.ToArray());

                    if (members.Length > index.intValue)
                    {
                        array_element.FindPropertyRelative("callback_is_field").boolValue = (members[index.intValue].MemberType == MemberTypes.Field);
                        array_element.FindPropertyRelative("callback_name").stringValue   = members[index.intValue].Name;
                        array_element.FindPropertyRelative("parameter").FindPropertyRelative("_name").stringValue = parameter_name;
                    }
                }
                EditorGUI.indentLevel -= 1;
            }

            SerializedProperty states_property         = new SerializedObject(state_machine_property.objectReferenceValue).FindProperty("states");
            SerializedProperty coroutine_list_property = serialized_target.FindProperty("state_coroutine_list");

            states_foldout = EditorGUILayout.Foldout(states_foldout, "States");
            if (states_foldout)
            {
                EditorGUI.indentLevel += 1;
                for (int i = 0; i < coroutine_list_property.arraySize; i++)
                {
                    SerializedProperty array_element = coroutine_list_property.GetArrayElementAtIndex(i);
                    string             state_name    = states_property.GetArrayElementAtIndex(i).FindPropertyRelative("_name").stringValue;
                    SerializedProperty index         = array_element.FindPropertyRelative("coroutine_index");

                    index.intValue = EditorGUILayout.Popup(state_name, index.intValue, state_candidate_names.ToArray());

                    if (state_candidate_names.Count > index.intValue)
                    {
                        array_element.FindPropertyRelative("coroutine_name").stringValue = state_candidate_names[index.intValue];
                        array_element.FindPropertyRelative("state").FindPropertyRelative("_name").stringValue = state_name;
                    }
                }
                EditorGUI.indentLevel -= 1;
            }
        }

        EditorGUILayout.Space();

        DrawPropertiesExcluding(serialized_target, new string[] { "state_machine", "parameter_callback_list", "state_coroutine_list", "m_Script" });

        serialized_target.ApplyModifiedProperties();
    }
Exemplo n.º 3
0
    public override void OnInspectorGUI()
    {
        if (_da.gameObject.activeInHierarchy == false)
        {
            base.OnInspectorGUI();
            return;
        }

        MonoScript script;

        script = MonoScript.FromMonoBehaviour((DynamicAsset)target);
        script = EditorGUILayout.ObjectField("Script:", script, typeof(MonoScript), false) as MonoScript;

        GUILayout.Space(10f);
        serializedObject.Update();
        EditorGUILayout.PropertyField(serializedObject.FindProperty("autoLoad"), false);
        EditorGUILayout.PropertyField(serializedObject.FindProperty("textureReadonly"), false);
        EditorGUILayout.PropertyField(serializedObject.FindProperty("cacheAsset"), false);
        if (!_da.cacheAsset)
        {
            EditorGUILayout.PropertyField(serializedObject.FindProperty("autoDisposeAsset"), false);
        }
        EditorGUILayout.PropertyField(serializedObject.FindProperty("_url"), false);
        //路径有变化
        if (!Application.isPlaying && _da.asset != null && !string.IsNullOrEmpty(_da.url) && !_da.url.Equals(_da.asset.url))
        {
            _da.frameName = "";
            _da.RemoveSprite(true);
        }

        var        dragArea = GUILayoutUtility.GetRect(0f, 35f, GUILayout.ExpandWidth(true));
        GUIContent title    = new GUIContent("Drag Object here from StreamingAssets");

        GUI.Box(dragArea, title);

        if (_da.url.LastIndexOf(".xml") > 0)
        {
//			EditorGUILayout.PropertyField(serializedObject.FindProperty("_frameName"), false);
            //用列表显示
            if (!Application.isPlaying && _da.asset != null && _da.asset.sprites == null)
            {
                _da.LoadSprite();
            }
            if (_da.asset != null && _da.asset.sprites != null)
            {
                int selctedIndex = -1;
                System.Collections.Generic.List <string> animsList = new System.Collections.Generic.List <string>(_da.asset.sprites.Count + 1);
                int i = 0;
                foreach (string n in _da.asset.sprites.Keys)
                {
                    if (n.Equals(_da.frameName))
                    {
                        selctedIndex = i;
                    }
                    animsList.Add(n);
                    ++i;
                }
                animsList.Insert(0, "<None>");

                int temp = EditorGUILayout.Popup("Sprite Frames", selctedIndex + 1, animsList.ToArray()) - 1;
                if (selctedIndex != temp)
                {
                    if (temp == -1)
                    {
                        _da.frameName = "";
                    }
                    else
                    {
                        _da.frameName = animsList[temp + 1];
                    }
                    UnityEditor.EditorUtility.SetDirty(_da);
                    if (!Application.isPlaying && !string.IsNullOrEmpty(_da.gameObject.scene.name))
                    {
                        UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene());
                    }
                }
            }
        }
        else
        {
            GUILayout.Space(10f);
            EditorGUILayout.PropertyField(serializedObject.FindProperty("replaceMatTexture"), false);
            if (_da.replaceMatTexture)
            {
                EditorGUILayout.PropertyField(serializedObject.FindProperty("material"), false);
                EditorGUILayout.PropertyField(serializedObject.FindProperty("nameId"), false);
                EditorGUILayout.PropertyField(serializedObject.FindProperty("restoreOnDisable"), false);
                if (_da.restoreOnDisable)
                {
                    EditorGUILayout.PropertyField(serializedObject.FindProperty("prevTex"), false);
                }
            }
            else if (_da.material != null && _da.prevTex != null)
            {
                _da.material.SetTexture(_da.nameId, _da.prevTex);
            }
        }
        EditorGUILayout.PropertyField(serializedObject.FindProperty("onInited"), false);
        serializedObject.ApplyModifiedProperties();

        GUILayout.Space(10f);
        if (GUILayout.Button("Refresh", GUILayout.Height(20)))
        {
            _da.LoadSprite();
        }

        DropEvent(dragArea);
    }
    void OnGUI()
    {
        if (DragAndDrop.objectReferences.Length == 0)
        {
            return;
        }

        if (Event.current.type == EventType.MouseMove || Event.current.type == EventType.DragUpdated)
        {
            HadMouseOver = true;
        }

        int items = 0;
        //EditorGUIUtility.LookLikeInspector();

        Object dragging = DragAndDrop.objectReferences[0];
        string note;

        foreach (Component component in _target.GetComponents <Component>())
        {
            bool drawnHeader = false;
            Type type        = component.GetType();

            foreach (FieldInfo f in FieldsFor(type))
            {
                note = "";
                if (!IsCompatibleField(f, dragging, ref note))
                {
                    continue;
                }

                if (!drawnHeader)
                {
                    MonoScript ms = MonoScript.FromMonoBehaviour(component as MonoBehaviour);
                    string     s  = Path.GetFileName(AssetDatabase.GetAssetPath(ms));
                    EditorGUILayout.LabelField(s, EditorStyles.boldLabel);
                    drawnHeader = true;
                }

                UnityEngine.Object oldValue = (UnityEngine.Object)f.GetValue(component);
                EditorGUILayout.BeginHorizontal(GUILayout.Width(330.0f));
                GUILayout.Label("    " + f.Name, GUILayout.Width(150.0f));

                Object newValue;
                newValue = EditorGUILayout.ObjectField(oldValue, f.FieldType, true, GUILayout.Height(20), GUILayout.Width(250));

                if (newValue != oldValue)
                {
#if UNITY_4_3_PLUS
                    Undo.RecordObject(component, "Change field");
#else
                    Undo.RegisterUndo(component, "Change field");
#endif
                    f.SetValue(component, newValue);
                    EditorUtility.SetDirty(component.gameObject);
                    _close     = true;
                    _closeTime = System.DateTime.Now;
                }

                GUILayout.Label(note);

                EditorGUILayout.EndHorizontal();

                items++;
            }
        }

        if (items == 0)
        {
            GUILayout.Label("No suitable variables for " + dragging.GetType().ToString());
        }

        if (!_repositioned && Event.current.type == EventType.Repaint)
        {
            Rect r = GUILayoutUtility.GetLastRect();
            r.height += r.y + 4.0f;
            r.height  = Mathf.Max(r.height, 50.0f);

            float newY = _desiredPosition.y - r.height / 2;
            float newX = _desiredPosition.x - 500.0f;

            if (newY < 0)
            {
                newY = 0;
            }
            else if (newY + r.height > Screen.currentResolution.height - 32)
            {
                newY = Screen.currentResolution.height - r.height - 32;
            }

            position = new Rect(newX, newY, 500.0f, r.height);

            _repositioned = true;
        }

        GUI.DrawTexture(new Rect(0, 0, position.width, 1), EditorGUIUtility.whiteTexture);
        GUI.DrawTexture(new Rect(0, 0, 1, position.height), EditorGUIUtility.whiteTexture);
        GUI.DrawTexture(new Rect(0, position.height - 1, position.width, 1), EditorGUIUtility.whiteTexture);
        GUI.DrawTexture(new Rect(position.width - 1, 0, 1, position.height), EditorGUIUtility.whiteTexture);
    }
Exemplo n.º 5
0
 private void OnEnable()
 {
     M      = (MItem)target;
     script = MonoScript.FromMonoBehaviour((MonoBehaviour)target);
 }
Exemplo n.º 6
0
 private void OnEnable()
 {
     M      = (Mountable)target;
     script = MonoScript.FromMonoBehaviour(M);
 }
Exemplo n.º 7
0
    public override void OnInspectorGUI()
    {
        serializedObject.Update();

        // Add clickable script field, as would have been provided by DrawDefaultInspector()
        MonoScript script = MonoScript.FromMonoBehaviour(target as MonoBehaviour);

        EditorGUI.BeginDisabledGroup(true);
        EditorGUILayout.ObjectField("Script", script, typeof(MonoScript), false);
        EditorGUI.EndDisabledGroup();

        CreateStylesAndContent();

        EditorGUILayout.PropertyField(triggerTransformProperty);
        EditorGUILayout.PropertyField(controllerrenderer, true);

        // Show all properties except for display state.
        EditorGUILayout.PropertyField(attachmentPrefabs, true);
        EditorGUILayout.PropertyField(touchPadColor);
        EditorGUILayout.PropertyField(appButtonColor);
        EditorGUILayout.PropertyField(systemButtonColor);
        EditorGUILayout.PropertyField(triggerButtonColorProperty);
        EditorGUILayout.PropertyField(readControllerState);

        // Determine if the display state can currently be edited in the inspector.
        bool allowEditDisplayState = !readControllerState.boolValue || !Application.isPlaying;

        if (!allowEditDisplayState)
        {
            // Prevents editing the display state in the inspector.
            GUI.enabled = false;
        }

        Rect displayStateRect = EditorGUILayout.BeginVertical();

        GUI.Box(displayStateRect, "");

        // Show the display state header.
        EditorGUILayout.LabelField(displayStateHeaderContent,
                                   displayStateHeaderStyle,
                                   GUILayout.Height(displayStateHeaderHeight));

        // Indent the display state properties.
        EditorGUI.indentLevel++;

        // Iterate through the child properties of the displayState property.
        SerializedProperty iter        = displayState.Copy();
        SerializedProperty nextElement = displayState.Copy();
        bool hasNextElement            = nextElement.Next(false);

        iter.NextVisible(true);
        do
        {
            // It iter is the same as nextElement, then the iter has moved beyond the children of the
            // display state which means it has finished showing the display state.
            if (hasNextElement && SerializedProperty.EqualContents(nextElement, iter))
            {
                break;
            }

            GUIContent content = new GUIContent(DISPLAY_STATE_ITEM_PREFIX + iter.displayName);
            EditorGUILayout.PropertyField(iter, content);
        } while (iter.NextVisible(false));

        // End the vertical region and draw the box.
        EditorGUI.indentLevel--;
        EditorGUILayout.Space();
        EditorGUILayout.EndVertical();

        // Reset GUI.enabled.
        if (!allowEditDisplayState)
        {
            GUI.enabled = true;
        }

        EditorGUILayout.PropertyField(maximumAlpha);

        serializedObject.ApplyModifiedProperties();
    }
Exemplo n.º 8
0
 protected void DrawScriptField(MonoBehaviour script_type, System.Type object_type)
 {
     EditorGUI.BeginDisabledGroup(true);
     EditorGUILayout.ObjectField("Script: ", MonoScript.FromMonoBehaviour(script_type), object_type, false);
     EditorGUI.EndDisabledGroup();
 }
Exemplo n.º 9
0
        /// <summary>
        /// Draw the contents of the GUI.Window.
        /// <param name="id">The unique id of the window.</param>
        /// </summary>
        void StateGUIWindow(int id)
        {
            // Draw the name and the icon state
            Rect rectName = new Rect(0, 12f, defaultWidth, c_WindowTitleHeight);

            GUI.Label(rectName, new GUIContent(m_State.stateName, m_Icon), s_Styles.windowTitle);

            // If this state is enabled then draw the enabled bar
            if (Application.isPlaying && m_State.enabled && Event.current.type == EventType.Repaint)
            {
                // Get the background position
                Rect backgroundPos = s_Styles.enabledBarBackground.margin.Remove(new Rect(0f, rectName.yMax + 5f, defaultWidth, 10f));

                // Get the foreground position
                Rect foregroundPos = s_Styles.enabledBarBackground.padding.Remove(backgroundPos);
                foregroundPos.width = foregroundPos.width * Mathf.Repeat(Time.time, 1f);

                // Draw foreground bar
                s_Styles.enabledBar.Draw(foregroundPos, false, false, false, false);
                // Draw background
                s_Styles.enabledBarBackground.Draw(backgroundPos, false, false, false, false);
            }


            if (m_TransitionGUIs != null)
            {
                // Get the current event
                Event current = Event.current;

                // It's a repaint event?
                if (current.type == EventType.Repaint)
                {
                    DrawEventName();
                }
                // It's a mouse down event?
                else if (current.type == EventType.MouseDown)
                {
                    // Create the rect
                    Rect rect = new Rect(0, StateGUI.defaultHeight - 2, StateGUI.defaultWidth, TransitionGUI.defaultHeight);
                    // Get the mouseposition
                    Vector2 mousePos = current.mousePosition;

                    // Logic for mouse click in event names
                    for (int i = 0; i < m_TransitionGUIs.Count; i++)
                    {
                        if (rect.Contains(mousePos))
                        {
                            if (Event.current.button == 1)
                            {
                                BehaviourWindow.activeState      = m_State;
                                BehaviourWindow.activeTransition = m_TransitionGUIs[i].transition;
                                ShowContextMenu(m_TransitionGUIs[i].transition);
                                Event.current.Use();
                            }
                            else if (Event.current.button == 0)
                            {
                                BehaviourWindow.activeState      = m_State;
                                BehaviourWindow.activeTransition = m_TransitionGUIs[i].transition;
                                TransitionDragAndDrop.PrepareStartDrag(m_TransitionGUIs[i], this); // Should always be called after BehaviourWindow.activeTransition
                                Event.current.Use();
                            }
                        }
                        // Update rect.y pos
                        rect.y += TransitionGUI.defaultHeight;
                    }
                }
            }

            switch (Event.current.type)
            {
            // Is mouse button down?
            case EventType.MouseDown:
                if (Event.current.button == 1)
                {
                    OnContextMenu();
                    Event.current.Use();
                }
                // Is the left mouse button?
                else if (Event.current.button == 0)
                {
                    // Focus in this window
                    s_DraggedWindow = id;
                    // Select this state?
                    if (BehaviourWindow.activeStates.Length <= 1)
                    {
                        BehaviourWindow.activeState = m_State;
                    }
                    // Unselect transition
                    BehaviourWindow.activeTransition = null;

                    // Double click?
                    if (Event.current.clickCount >= 2)
                    {
                        // The state is a parent state?
                        if (m_State is ParentBehaviour)
                        {
                            // Selects the parent state
                            BehaviourWindow.activeParent = m_State as ParentBehaviour;
                            Event.current.Use();
                        }
                        // The state is a MonoScript?
                        else if (m_State is InternalMonoState)
                        {
                            // Selects the MonoBehaviour game object.
                            var monoState = m_State as InternalMonoState;
                            if (monoState.monoBehaviour != null)
                            {
                                Selection.activeGameObject = monoState.monoBehaviour.gameObject;
                                Event.current.Use();
                            }
                        }
                        // Opens the state script
                        else
                        {
                            var monoScript = MonoScript.FromMonoBehaviour(m_State);     // Gets the script.
                            if (monoScript != null)
                            {
                                AssetDatabase.OpenAsset(monoScript);        // Opens script in default application.
                                Event.current.Use();
                            }
                        }
                    }
                }
                break;

            // Mouse button up?
            case EventType.MouseUp:
                if (s_DraggedWindow == id)
                {
                    s_DraggedWindow = -1;
                }
                break;
            }

            // GUI.DragWindow();
            DragStateGUIs();
        }
Exemplo n.º 10
0
 public static void MonoBehaviourTitle(MonoBehaviour target)
 {
     GUI.enabled = false;
     EditorGUILayout.ObjectField("Script", MonoScript.FromMonoBehaviour(target), typeof(MonoScript), false);
     GUI.enabled = true;
 }
Exemplo n.º 11
0
    public override void OnInspectorGUI()
    {
        serializedObject.Update();

        // Display the script inside the inspector
        GUI.enabled = false;
        EditorGUILayout.ObjectField("Script", MonoScript.FromMonoBehaviour((MonoBehaviour)target), typeof(Shape), false);
        GUI.enabled = true;

        EditorGUILayout.PropertyField(typeProp);
        EditorGUILayout.PropertyField(defaultRotationProp);
        EditorGUILayout.PropertyField(currentRotationIndexProp);
        EditorGUILayout.PropertyField(rotationStateProp);

        //DisplayListTogether(rotationStateArrayProp, rotationArrayProp, offSetListProp);

        if (GUILayout.Button("Add to List"))
        {
            rotationStateArrayProp.arraySize++;
            rotationArrayProp.arraySize++;

            // offSetListProp is a 2d list
            offSetListProp.arraySize++;
        }

        InsertSpaces(2);

        if (GUILayout.Button("Clear All"))
        {
            targetShape.ClearAll();
        }

        InsertSpaces(2);

        for (int i = 0; i < rotationArrayProp.arraySize; i++)
        {
            EditorGUILayout.LabelField("Element (" + i.ToString() + ")");
            StartVertical();

            SerializedProperty sp  = rotationStateArrayProp.GetArrayElementAtIndex(i);
            SerializedProperty sp2 = rotationArrayProp.GetArrayElementAtIndex(i);

            EditorGUILayout.PropertyField(sp, new GUIContent("Rotation State"));
            EditorGUILayout.PropertyField(sp2, new GUIContent("Rotation"));

            SerializedProperty sp3     = offSetListProp.GetArrayElementAtIndex(i);
            SerializedProperty sp3List = sp3.FindPropertyRelative("offsets");

            EditorGUILayout.BeginHorizontal();

            EditorGUILayout.LabelField("Rotation Offsets");
            if (GUILayout.Button("+", GUILayout.Width(30)))
            {
                sp3List.arraySize++;
            }
            if (GUILayout.Button("-", GUILayout.Width(30)))
            {
                sp3List.DeleteArrayElementAtIndex(sp3List.arraySize - 1);
            }

            EditorGUILayout.EndHorizontal();

            EditorGUI.indentLevel++;
            for (int j = 0; j < sp3List.arraySize; j++)
            {
                EditorGUILayout.PropertyField(sp3List.GetArrayElementAtIndex(j));
            }
            EditorGUI.indentLevel--;


            if (GUILayout.Button("Remove This Index (" + i.ToString() + ")"))
            {
                rotationStateArrayProp.DeleteArrayElementAtIndex(i);
                rotationArrayProp.DeleteArrayElementAtIndex(i);
                offSetListProp.DeleteArrayElementAtIndex(i);
            }

            EndVertical();
            InsertSpaces(1);
        }

        if (GUILayout.Button("Preview Rotation"))
        {
            targetShape.PreviewRotation();
        }

        if (GUILayout.Button("Preview Rotation Offsets"))
        {
            targetShape.PreviewOffSets();
        }

        //if (GUILayout.Button("Print")) {
        //    targetShape.Print();
        //}

        serializedObject.ApplyModifiedProperties();
    }
        void OnGUICallBack()
        {
            //findMethodName = EditorGUILayout.TextField ("extra callback", findMethodName, GUILayout.Width (Screen.width - 8));

            if (callbackCallObjectList.Count != 0)
            {
                current = EditorGUILayout.BeginScrollView(current);

                for (int i = 0; i < callbackCallObjectList.Count; i++)
                {
                    EditorGUILayout.BeginHorizontal("box", GUILayout.Width(Screen.width - 8));
                    var methodName = callbackCallObjectList [i];

                    EditorGUI.BeginChangeCheck();
                    if (EditorGUILayout.ToggleLeft(methodName.method, i == currentItem))
                    {
                        currentItem = i;
                    }
                    if (EditorGUI.EndChangeCheck())
                    {
                        UpdateComponentHaveCallbackList();
                    }

                    EditorGUILayout.BeginVertical();

                    switch (callType)
                    {
                    case CallType.CallingComponents:
                        if (i == currentItem)
                        {
                            foreach (var obj in methodName.callComponent)
                            {
                                EditorGUILayout.ObjectField(obj.GetType().ToString(), obj, obj.GetType());
                            }
                            if (methodName.callComponent.Count == 0)
                            {
                                EditorGUILayout.LabelField("Call from UnityEngine");
                            }
                        }
                        break;

                    case CallType.CalledComponents:

                        if (i == currentItem)
                        {
                            var monoscriptList = new List <MonoScript>();

                            foreach (var item in componentHaveCallbackList)
                            {
                                var code = MonoScript.FromMonoBehaviour(item.component);
                                if (!monoscriptList.Contains(code))
                                {
                                    monoscriptList.Add(code);
                                }
                            }

                            foreach (var obj in monoscriptList)
                            {
                                if (obj == null)
                                {
                                    break;
                                }
                                EditorGUILayout.ObjectField(obj, typeof(MonoScript), true);
                            }
                        }

                        break;

                    case CallType.CalledObjects:
                        if (i == currentItem)
                        {
                            var objList = new List <GameObject>();
                            foreach (var item in componentHaveCallbackList)
                            {
                                if (!objList.Contains(item.component.gameObject))
                                {
                                    objList.Add(item.component.gameObject);
                                }
                            }


                            foreach (var obj in objList)
                            {
                                if (obj == null)
                                {
                                    break;
                                }

                                EditorGUILayout.ObjectField(obj, obj.GetType());
                            }
                        }
                        break;
                    }

                    EditorGUILayout.EndVertical();

                    EditorGUILayout.EndHorizontal();
                }

                EditorGUILayout.EndScrollView();
            }
        }
Exemplo n.º 13
0
        /// <inheritdoc />
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            if (property.objectReferenceValue != null)
            {
                using (var serializedObject = new SerializedObject(property.objectReferenceValue))
                {
                    // First, render a header for the TileLayer.

                    if (serializedObject == null)
                    {
                        EditorGUI.LabelField(position, property.objectReferenceValue.GetType().Name);
                        return;
                    }

                    var tileLayer = (TileLayer)property.GetValue();
                    if (tileLayer == null)
                    {
                        return;
                    }

                    var script = MonoScript.FromMonoBehaviour(tileLayer);

                    var tileLayerNamePosition = position;
                    EditorGUILayout.BeginHorizontal();
                    {
                        Undo.RecordObject(serializedObject.targetObject, "Enabled");
                        var iconPosition = position;
                        iconPosition.height = EditorGUIUtility.singleLineHeight;
                        iconPosition.width  = iconPosition.height;
                        GUI.Box(iconPosition, AssetPreview.GetMiniThumbnail(script), GUIStyle.none);

                        var togglePosition = iconPosition;
                        togglePosition.x    += 4 + EditorStyles.toggle.padding.left;
                        togglePosition.width = EditorStyles.toggle.padding.left;
                        var customToggleStyle = new GUIStyle(EditorStyles.toggle)
                        {
                            alignment = TextAnchor.MiddleCenter
                        };
                        tileLayer.enabled = EditorGUI.Toggle(togglePosition, tileLayer.enabled, customToggleStyle);
                        serializedObject.Update();

                        var name      = ObjectNames.NicifyVariableName(script.name) + " (Script)";
                        var labelSize = EditorStyles.boldLabel.CalcSize(new GUIContent(name));
                        tileLayerNamePosition.height = EditorGUIUtility.singleLineHeight;
                        tileLayerNamePosition.x     += 4 + EditorStyles.toggle.padding.left;
                        tileLayerNamePosition.width  = labelSize.x + EditorStyles.toggle.padding.left;
                        EditorGUI.LabelField(tileLayerNamePosition, new GUIContent(name), EditorStyles.boldLabel);
                    }
                    EditorGUILayout.EndHorizontal();

                    var fieldRect = new Rect(position)
                    {
                        height = EditorGUIUtility.singleLineHeight
                    };
                    var propertyRects = new List <Rect>();
                    fieldRect.xMin += 5;
                    var marchingRect = new Rect(fieldRect);
                    marchingRect.y += marchingRect.height + EditorGUIUtility.standardVerticalSpacing;

                    // For the content of the TileLayer, either automatically generate UI for the fields,
                    // or defer to the CustomTileLayerDrawer.

                    EditorGUI.indentLevel++;

                    if (_propertyDrawerCache.Value.TryGetValue(property.objectReferenceValue.GetType(), out var propertyDrawer))
                    {
                        // Property has a drawer... use that to display.
                        propertyDrawer.OnGUI(marchingRect, property, label);
                    }
                    else
                    {
                        // Property does not have a drawer, use a draw that shows all the serialized fields.
                        var field = serializedObject.GetIterator();
                        field.NextVisible(true);

                        while (field.NextVisible(false))
                        {
                            marchingRect.height = EditorGUI.GetPropertyHeight(field, true);
                            propertyRects.Add(marchingRect);
                            marchingRect.y += marchingRect.height + EditorGUIUtility.standardVerticalSpacing;
                        }

                        int index = 0;
                        field = serializedObject.GetIterator();
                        field.NextVisible(true);

                        //Replacement for "editor.OnInspectorGUI ();" so we have more control on how we draw the editor
                        while (field.NextVisible(false))
                        {
                            try
                            {
                                EditorGUI.PropertyField(propertyRects[index], field, true);
                            }
                            catch (StackOverflowException)
                            {
                                field.objectReferenceValue = null;
                                Debug.LogError(
                                    "Detected self-nesting causing a StackOverflowException, avoid using the same object inside a nested structure.");
                            }

                            ++index;
                        }
                    }

                    serializedObject.ApplyModifiedProperties();

                    EditorGUI.indentLevel--;

                    // Shows context menu for editing the associated script, i.e. will open text editor like Visual Studio.
                    var currentEvent = Event.current;
                    if (currentEvent.type == EventType.ContextClick)
                    {
                        if (tileLayerNamePosition.Contains(currentEvent.mousePosition))
                        {
                            if (script != null)
                            {
                                GenericMenu menu = new GenericMenu();
                                menu.AddItem(new GUIContent("Edit Script"), false, () => AssetDatabase.OpenAsset(script));
                                menu.ShowAsContext();
                            }
                        }
                    }
                }
            }
            else
            {
                EditorGUI.LabelField(position, "Unknown");
            }
        }
Exemplo n.º 14
0
        private void Draw(int pInstanceID, Rect pDrawingRect)
        {
            // called per-line in the hierarchy window

            GameObject gameObject = EditorUtility.InstanceIDToObject(pInstanceID) as GameObject;

            if (gameObject == null)
            {
                return;
            }

            bool currentLock = (gameObject.hideFlags & HideFlags.NotEditable) != 0;

            bool doPreview    = Common.Modifier(_setting_showHoverPreview, _setting_showHoverPreviewShift, _setting_showHoverPreviewCtrl, _setting_showHoverPreviewAlt);
            bool doTooltip    = Common.Modifier(_setting_showHoverTooltip, _setting_showHoverTooltipShift, _setting_showHoverTooltipCtrl, _setting_showHoverTooltipAlt);
            bool doComponents = Common.Modifier(_setting_showComponents, _setting_showComponentsShift, _setting_showComponentsCtrl, _setting_showComponentsAlt);
            bool doEnabled    = Common.Modifier(_setting_showEnabled, _setting_showEnabledShift, _setting_showEnabledCtrl, _setting_showEnabledAlt);
            bool doLockIcon   = Common.Modifier(_setting_showLock, _setting_showLockShift, _setting_showLockCtrl, _setting_showLockAlt);

            doLockIcon |= _setting_showLock && _setting_showLockLocked && currentLock;

            Object dragging = DragAndDrop.objectReferences.Length == 1 ? DragAndDrop.objectReferences[0] : null;

            string tooltip = "";

            Color originalColor = GUI.color;

            if (doEnabled)
            {
                Rect r = pDrawingRect;
                r.x     = r.x + r.width - 14;
                r.width = 12;

                bool bNewActive = GUI.Toggle(r, gameObject.activeSelf, "");
                if (bNewActive != gameObject.activeSelf)
                {
                    gameObject.SetActive(bNewActive);
                }

                pDrawingRect.width -= 14;
            }

            if (doLockIcon)
            {
                Rect r = pDrawingRect;
                r.x     = r.x + r.width - 14;
                r.width = 12;

                GUI.color = currentLock ? new Color(1, 1, 1, 1) : new Color(1, 1, 1, 0.4f);

                bool newLock = GUI.Toggle(r, currentLock, "", (GUIStyle)"IN LockButton");
                if (newLock != currentLock)
                {
                    if (newLock)
                    {
                        UpdateLock(gameObject, true);
                    }
                    else
                    {
                        UpdateLock(gameObject, false);
                    }
                }

                GUI.color = originalColor;

                pDrawingRect.width -= 14;
            }

            float width = EditorStyles.label.CalcSize(new GUIContent(gameObject.name)).x;

            if (((1 << gameObject.layer) & Tools.visibleLayers) == 0)
            {
                Rect labelRect = pDrawingRect;
                labelRect.width = width;
                labelRect.x    -= 2;
                labelRect.y    -= 4;
                GUI.Label(labelRect, "".PadRight(gameObject.name.Length, '_'));
            }

            if (gameObject == dragging && _draggingShownQuickInspector)
            {
                Rect labelRect = pDrawingRect;

                labelRect.width = width;
                labelRect.x    -= 2;
                labelRect.y    += 1;

                GUI.color = Color.red;
                GUI.DrawTexture(new Rect(labelRect.x, labelRect.y, labelRect.width, 1), EditorGUIUtility.whiteTexture);
                GUI.DrawTexture(new Rect(labelRect.x, labelRect.y, 1, labelRect.height), EditorGUIUtility.whiteTexture);
                GUI.DrawTexture(new Rect(labelRect.x, labelRect.yMax, labelRect.width, 1), EditorGUIUtility.whiteTexture);
                GUI.DrawTexture(new Rect(labelRect.xMax, labelRect.y, 1, labelRect.height), EditorGUIUtility.whiteTexture);
            }

            if (doTooltip)
            {
                tooltip = GetTooltip(gameObject);
                if (tooltip.Length > 0)
                {
                    GUI.Label(pDrawingRect, new GUIContent(" ", tooltip));
                }
            }

            if (doComponents)
            {
                Rect iconRect = pDrawingRect;
                iconRect.x = pDrawingRect.x + pDrawingRect.width - 16;
                iconRect.y--;
                iconRect.width  = 16;
                iconRect.height = 16;

                _mousePosition = new Vector2(Event.current.mousePosition.x + Common.HierarchyWindow.position.x, Event.current.mousePosition.y + Common.HierarchyWindow.position.y);

                bool mouseIn = pDrawingRect.Contains(Event.current.mousePosition);

                if (doPreview && mouseIn)
                {
                    _hoverObject = gameObject;
                }

                if (DragAndDrop.objectReferences.Length == 1 && _setting_showHoverDropWindow && mouseIn)
                {
                    if (_draggingHeldOver == null)
                    {
                        _draggingHeldStart = System.DateTime.Now;
                    }

                    if (_draggingHeldOver != gameObject)
                    {
                        _draggingShownQuickInspector = false;
                    }

                    _draggingHeldOver = gameObject;
                }

                bool   suitableDrop = false;
                bool   drawnEtc     = false;
                string tempNote     = "";

                foreach (Component c in gameObject.GetComponents <Component>())
                {
                    if (c is Transform)
                    {
                        continue;
                    }

                    if (c != null && !suitableDrop && dragging != null)
                    {
                        Type type = c.GetType();
                        foreach (FieldInfo f in TeneDropTarget.FieldsFor(type))
                        {
                            if (TeneDropTarget.IsCompatibleField(f, dragging, ref tempNote))
                            {
                                suitableDrop = true;
                                break;
                            }
                        }
                    }

                    if (c == null)
                    {
                        Rect rectX = new Rect(iconRect.x + 4, iconRect.y + 1, 14, iconRect.height);
                        GUI.color = new Color(1.0f, 0.35f, 0.35f, 1.0f);
                        GUI.Label(rectX, new GUIContent("X", "Missing Script"), Common.ColorLabel(new Color(1.0f, 0.35f, 0.35f, 1.0f)));
                        iconRect.x -= 9;

                        if (rectX.Contains(Event.current.mousePosition))
                        {
                            _hoverObject = null;
                        }

                        continue;
                    }

                    GUI.color = c.GetEnabled() ? Color.white : new Color(0.5f, 0.5f, 0.5f, 0.5f);

                    if (iconRect.x < pDrawingRect.x + width)
                    {
                        if (!drawnEtc)
                        {
                            GUI.Label(iconRect, " ..");
                            drawnEtc = true;
                        }
                        continue;
                    }

                    if (doTooltip)
                    {
                        tooltip = GetTooltip(c);
                    }

                    Texture iconTexture = null;

                    if (c is MonoBehaviour)
                    {
                        MonoScript ms = MonoScript.FromMonoBehaviour(c as MonoBehaviour);
                        iconTexture = AssetDatabase.GetCachedIcon(AssetDatabase.GetAssetPath(ms));
                    }

                    if (iconTexture == null)
                    {
                        iconTexture = Common.GetMiniThumbnail(c);
                    }

                    if (iconTexture != null)
                    {
                        if (doPreview)
                        {
                            if (iconRect.Contains(Event.current.mousePosition))
                            {
                                _hoverObject = c;
                            }
                        }

                        GUI.DrawTexture(iconRect, iconTexture, ScaleMode.ScaleToFit);
                        if (GUI.Button(iconRect, new GUIContent("", tooltip), EditorStyles.label))
                        {
                            c.SetEnabled(!c.GetEnabled());
                            Common.HierarchyWindow.Repaint();
                            return;
                        }
                        iconRect.x -= iconRect.width;
                    }
                }

                if (suitableDrop)
                {
                    Rect labelRect = pDrawingRect;

                    labelRect.width = width;
                    labelRect.x    -= 2;
                    labelRect.y    += 1;

                    GUI.color = Color.white;
                    GUI.DrawTexture(new Rect(labelRect.x, labelRect.y, labelRect.width, 1), EditorGUIUtility.whiteTexture);
                    GUI.DrawTexture(new Rect(labelRect.x, labelRect.y, 1, labelRect.height), EditorGUIUtility.whiteTexture);
                    GUI.DrawTexture(new Rect(labelRect.x, labelRect.yMax, labelRect.width, 1), EditorGUIUtility.whiteTexture);
                    GUI.DrawTexture(new Rect(labelRect.xMax, labelRect.y, 1, labelRect.height), EditorGUIUtility.whiteTexture);

                    if (mouseIn)
                    {
                        DragAndDrop.visualMode = DragAndDropVisualMode.Generic;
                    }

                    if (_draggingHeldOver == gameObject)
                    {
                        GUI.DrawTexture(new Rect(0, labelRect.y + labelRect.height / 2.0f, labelRect.x, 1), EditorGUIUtility.whiteTexture);
                    }
                }
            }

            GUI.color = originalColor;
        }
Exemplo n.º 15
0
        /// <summary>
        /// OnInspectorGUI.
        /// </summary>
        public override void OnInspectorGUI()
        {
            EditorGUILayout.ObjectField("Script", MonoScript.FromMonoBehaviour(mScript), typeof(MyUGUIOrientationAnchor), false);

            bool isPortrait = true;

            if (!Application.isPlaying)
            {
                System.Type T = System.Type.GetType("UnityEditor.GameView,UnityEditor");
                System.Reflection.MethodInfo getSizeOfMainGameView = T.GetMethod("GetSizeOfMainGameView", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
                Vector2 resolution = (Vector2)getSizeOfMainGameView.Invoke(null, null);
                isPortrait = resolution.x < resolution.y;
            }
            else
            {
                isPortrait = Screen.width < Screen.height;
            }

            serializedObject.Update();

            EditorGUILayout.LabelField(string.Empty);
            mDelayAnchorTime.floatValue = EditorGUILayout.FloatField("Delay Anchor Time", mDelayAnchorTime.floatValue);

            EditorGUILayout.LabelField(string.Empty);
            GUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("Portrait" + (isPortrait ? " (Current)" : string.Empty), EditorStyles.boldLabel);
            if (GUILayout.Button("Use Current Anchor", GUILayout.MaxWidth(135)))
            {
                mPortraitPivot.vector2Value     = mRectTransform.pivot;
                mPortraitAnchorMin.vector2Value = mRectTransform.anchorMin;
                mPortraitAnchorMax.vector2Value = mRectTransform.anchorMax;
                mPortraitOffsetMin.vector2Value = mRectTransform.offsetMin;
                mPortraitOffsetMax.vector2Value = mRectTransform.offsetMax;
            }
            GUILayout.EndHorizontal();
            mPortraitPivot.vector2Value     = EditorGUILayout.Vector2Field("   Pivot", mPortraitPivot.vector2Value);
            mPortraitAnchorMin.vector2Value = EditorGUILayout.Vector2Field("   Anchor Min", mPortraitAnchorMin.vector2Value);
            mPortraitAnchorMax.vector2Value = EditorGUILayout.Vector2Field("   Anchor Max", mPortraitAnchorMax.vector2Value);
            mPortraitOffsetMin.vector2Value = EditorGUILayout.Vector2Field("   Offset Min", mPortraitOffsetMin.vector2Value);
            mPortraitOffsetMax.vector2Value = EditorGUILayout.Vector2Field("   Offset Max", mPortraitOffsetMax.vector2Value);

            EditorGUILayout.LabelField(string.Empty);
            GUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("Landscape" + (!isPortrait ? " (Current)" : string.Empty), EditorStyles.boldLabel);
            if (GUILayout.Button("Use Current Anchor", GUILayout.MaxWidth(135)))
            {
                mLandscapePivot.vector2Value     = mRectTransform.pivot;
                mLandscapeAnchorMin.vector2Value = mRectTransform.anchorMin;
                mLandscapeAnchorMax.vector2Value = mRectTransform.anchorMax;
                mLandscapeOffsetMin.vector2Value = mRectTransform.offsetMin;
                mLandscapeOffsetMax.vector2Value = mRectTransform.offsetMax;
            }
            GUILayout.EndHorizontal();
            mLandscapePivot.vector2Value     = EditorGUILayout.Vector2Field("   Pivot", mLandscapePivot.vector2Value);
            mLandscapeAnchorMin.vector2Value = EditorGUILayout.Vector2Field("   Anchor Min", mLandscapeAnchorMin.vector2Value);
            mLandscapeAnchorMax.vector2Value = EditorGUILayout.Vector2Field("   Anchor Max", mLandscapeAnchorMax.vector2Value);
            mLandscapeOffsetMin.vector2Value = EditorGUILayout.Vector2Field("   Offset Min", mLandscapeOffsetMin.vector2Value);
            mLandscapeOffsetMax.vector2Value = EditorGUILayout.Vector2Field("   Offset Max", mLandscapeOffsetMax.vector2Value);

            EditorGUILayout.LabelField(string.Empty);
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Anchor Now", GUILayout.MaxWidth(135)))
            {
                mScript.Anchor();
            }
            GUILayout.EndHorizontal();

            serializedObject.ApplyModifiedProperties();
        }
Exemplo n.º 16
0
        //Draw the window
        void DrawNodeWindow()
        {
            if (isHidden)
            {
                return;
            }

            if (childrenCollapsed)
            {
                var r = new Rect(nodeRect.x, nodeRect.yMax + 10, nodeRect.width, 20);
                EditorGUIUtility.AddCursorRect(r, MouseCursor.Link);
                if (GUI.Button(r, "COLLAPSED", "box"))
                {
                    childrenCollapsed = false;
                }
            }

            GUI.color = isActive? Color.white : new Color(0.9f, 0.9f, 0.9f, 0.8f);
            GUI.color = Graph.currentSelection == this? new Color(0.9f, 0.9f, 1) : GUI.color;
            GUI.color = Application.isPlaying? new Color(0.9f, 0.9f, 0.9f) : GUI.color;
            nodeRect  = GUILayout.Window(ID, nodeRect, NodeWindowGUI, string.Empty, "window");

            GUI.Box(nodeRect, "", "windowShadow");
            GUI.color = new Color(1, 1, 1, 0.5f);
            GUI.Box(new Rect(nodeRect.x + 6, nodeRect.y + 6, nodeRect.width, nodeRect.height), "", "windowShadow");

            if (Application.isPlaying && status != Status.Resting)
            {
                if (status == Status.Success)
                {
                    GUI.color = successColor;
                }
                else if (status == Status.Running)
                {
                    GUI.color = runningColor;
                }
                else if (status == Status.Failure)
                {
                    GUI.color = failureColor;
                }
                else if (status == Status.Error)
                {
                    GUI.color = Color.red;
                }

                GUI.Box(nodeRect, "", "windowHighlight");
            }
            else
            {
                if (isSelected)
                {
                    GUI.color = restingColor;
                    GUI.Box(nodeRect, "", "windowHighlight");
                }
            }

            if (isSelected && GUIUtility.keyboardControl == 0 && Event.current.keyCode == KeyCode.Delete && Event.current.type == EventType.KeyUp)
            {
                Graph.PostGUI += delegate { graph.RemoveNode(this); }
            }
            ;

            GUI.color = Color.white;
            EditorGUIUtility.AddCursorRect(nodeRect, MouseCursor.Link);

/*
 *                      var assignable = this as ITaskAssignable;
 *                      if (assignable && assignable.task != null && assignable.task.agentIsOverride){
 *                              var overrideRect = new Rect(nodeRect.x, nodeRect.y-18, nodeRect.width, 18);
 *                              GUI.Box(overrideRect, assignable.task.agentInfo);
 *                      }
 */
        }

        //removes the text color that some nodes add with html tags
        string StripNameColor(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return(name);
            }
            if (name.StartsWith("<") && name.EndsWith(">"))
            {
                name = name.Replace(name.Substring(0, name.IndexOf(">") + 1), "");
                name = name.Replace(name.Substring(name.IndexOf("<"), name.LastIndexOf(">") + 1 - name.IndexOf("<")), "");
            }
            return(name);
        }

        //This is the callback function of the GUILayout.window. Everything here is INSIDE the node Window.
        void NodeWindowGUI(int ID)
        {
            ////TITLE///
            if (inIconMode)
            {
                GUI.color           = EditorGUIUtility.isProSkin? Color.white : new Color(0f, 0f, 0f, 0.7f);
                GUI.backgroundColor = new Color(0, 0, 0, 0);
                GUILayout.Box(icon);
                GUI.backgroundColor = Color.white;
                GUI.color           = Color.white;
            }
            else
            {
                var stripedTitle = StripNameColor(nodeName);
                if (!string.IsNullOrEmpty(stripedTitle))
                {
                    var title        = nodeName;
                    var defaultColor = "<color=#eed9a7>";
                    if (!EditorGUIUtility.isProSkin)
                    {
                        title        = StripNameColor(title);
                        defaultColor = "<color=#222222>";
                    }
                    GUILayout.Label("<b><size=12>" + defaultColor + title + "</color></size></b>", centerLabel);
                }
            }
            ///


            var e = Event.current;

/*
 *                  var scaleNodeRect= new Rect(nodeRect.width-10,nodeRect.height-10, 8, 8);
 *                  GUI.Box(scaleNodeRect, "", "nodeScaleBtn");
 *
 *                  ////CONTROLS////
 *                  if (Graph.allowClick && e.button == 0 && e.type == EventType.MouseDown && scaleNodeRect.Contains(e.mousePosition)){
 *                      inResizeMode = true;
 *                      e.Use();
 *                  }
 */

            if (Graph.allowClick && e.button != 2 && e.type == EventType.MouseDown)
            {
                Graph.currentSelection = this;
                nodeIsPressed          = true;

                if (e.button == 0 && e.clickCount == 2)
                {
                    if (this is INestedNode && (this as INestedNode).nestedGraph != null)
                    {
                        graph.nestedGraphView = (this as INestedNode).nestedGraph;
                        nodeIsPressed         = false;
                    }
                    else
                    {
                        AssetDatabase.OpenAsset(MonoScript.FromMonoBehaviour(this));
                    }
                    e.Use();
                }

                if (e.control)
                {
                    Graph.PostGUI += delegate { graph.primeNode = this; };
                    e.Use();
                }

                OnNodePicked();
            }

            if (e.type == EventType.MouseUp)
            {
                inResizeMode  = false;
                nodeIsPressed = false;
                if (this is IAutoSortable)
                {
                    Graph.PostGUI += delegate { SortConnectionsByPositionX(); }
                }
                ;
                OnNodeReleased();
            }

            ///

            ////STATUS MARK ICONS////
            if (Application.isPlaying)
            {
                var markRect = new Rect(5, 5, 15, 15);
                if (status == Status.Success)
                {
                    GUI.color = successColor;
                    GUI.Box(markRect, "", new GUIStyle("checkMark"));
                }
                else if (status == Status.Running)
                {
                    GUI.Box(markRect, "", new GUIStyle("clockMark"));
                }
                else if (status == Status.Failure)
                {
                    GUI.color = failureColor;
                    GUI.Box(markRect, "", new GUIStyle("xMark"));
                }
            }
            ///

            ////NODE GUI////
            GUI.color = Color.white;
            GUI.skin  = null;
            GUI.skin.label.richText = true;

            GUI.skin.label.alignment = TextAnchor.MiddleCenter;

            GUILayout.BeginVertical();

            OnNodeGUI();

            if (this is ITaskAssignable)
            {
                var assignable = this as ITaskAssignable;
                var missing    = MissingTask(assignable.serializedTask);
                if (missing != null)
                {
                    GUILayout.Label(missing);
                }
                else
                {
                    var task = (this as ITaskAssignable).task;
                    if (task != null)
                    {
                        GUILayout.Label(NCPrefs.showTaskSummary? task.summaryInfo : string.Format("<b>{0}</b>", task.name));
                    }
                    else
                    {
                        GUILayout.Label("No Task");
                    }
                }
            }

            GUILayout.EndVertical();

            GUI.skin.label.alignment = TextAnchor.UpperLeft;


            ////CONTEXT MENU////
            if (Graph.allowClick && e.button == 1 && e.type == EventType.MouseUp)
            {
                if (Graph.multiSelection.Count > 0)
                {
                    var menu = new GenericMenu();
                    menu.AddItem(new GUIContent("Delete Selected Nodes"), false, delegate { foreach (Node node in Graph.multiSelection)
                                                                                            {
                                                                                                graph.RemoveNode(node);
                                                                                            }
                                 });
                    menu.ShowAsContext();
                    e.Use();
                    return;
                }
                else
                {
                    var menu = new GenericMenu();
                    if (graph.primeNode != this && allowAsPrime)
                    {
                        menu.AddItem(new GUIContent("Make Start (CTRL+Click)"), false, delegate { graph.primeNode = this; });
                    }

                    if (this is INestedNode)
                    {
                        menu.AddItem(new GUIContent("Edit Nested (Double Click)"), false, delegate { graph.nestedGraphView = (this as INestedNode).nestedGraph; });
                    }

                    menu.AddItem(new GUIContent("Duplicate (CTRL+D)"), false, delegate { Duplicate(); });

                    if (inConnections.Count > 0)
                    {
                        menu.AddItem(new GUIContent(isActive? "Disable" : "Enable"), false, delegate { SetActive(!isActive); });
                    }

                    if (this is IAutoSortable && outConnections.Count > 0)
                    {
                        menu.AddItem(new GUIContent(childrenCollapsed? "Expand Children" : "Collapse Children"), false, delegate { childrenCollapsed = !childrenCollapsed; });
                    }

                    if (this is ITaskAssignable)
                    {
                        var assignable = this as ITaskAssignable;
                        if (assignable.task != null)
                        {
                            menu.AddItem(new GUIContent("Copy Assigned Task"), false, delegate { Task.copiedTask = assignable.task; });
                        }
                        else
                        {
                            menu.AddDisabledItem(new GUIContent("Copy Assigned Task"));
                        }

                        if (Task.copiedTask != null)
                        {
                            menu.AddItem(new GUIContent("Paste Assign Task"), false, delegate {
                                try
                                {
                                    var current     = assignable.task;
                                    assignable.task = Task.copiedTask;
                                    assignable.task = current;
                                }
                                catch
                                {
                                    Debug.LogWarning(string.Format("Copied Task '{0}'' is incompatible type for target node '{1}'", Task.copiedTask.name, this.name));
                                    return;
                                }

                                if (assignable.task == Task.copiedTask)
                                {
                                    return;
                                }

                                if (assignable.task != null)
                                {
                                    if (EditorUtility.DisplayDialog("Paste Task", string.Format("Node already has a Task assigned '{0}'. Replace assigned task with pasted task '{1}'?", assignable.task.name, Task.copiedTask.name), "YES", "NO"))
                                    {
                                        Undo.DestroyObjectImmediate(assignable.task);
                                    }
                                    else
                                    {
                                        return;
                                    }
                                }

                                assignable.task = Task.copiedTask.CopyTo(gameObject);
                            });
                        }
                        else
                        {
                            menu.AddDisabledItem(new GUIContent("Paste Assigned Task"));
                        }
                    }

                    OnContextMenu(menu);

                    menu.AddSeparator("/");
                    menu.AddItem(new GUIContent("Delete (DEL)"), false, delegate { graph.RemoveNode(this); });

                    menu.ShowAsContext();
                    e.Use();
                }
            }
            ///



            ////LAST (BUT NOT LEAST)///
            if (inResizeMode)
            {
                nodeRect.width  = Mathf.Max(e.mousePosition.x + 10, minSize.x);
                nodeRect.height = Mathf.Max(e.mousePosition.y + 10, minSize.y);
            }
            else
            if (Graph.allowClick && e.button != 2)
            {
                if (e.type == EventType.MouseDrag)
                {
                    foreach (Node node in Graph.multiSelection)
                    {
                        if (node != null)
                        {
                            Undo.RecordObject(node, "Move");
                            node.nodeRect.center += e.delta;
                        }
                    }
                }

                Undo.RecordObject(this, "Move");

                if (NCPrefs.doSnap && !e.shift && Graph.multiSelection.Count == 0 && nodeIsPressed)
                {
                    nodeRect.x = Mathf.Round(nodeRect.x / 15) * 15;
                    nodeRect.y = Mathf.Round(nodeRect.y / 15) * 15;
                }

                if (this is IAutoSortable && (e.shift || childrenCollapsed) && e.type == EventType.MouseDrag && nodeIsPressed)
                {
                    RecursivePanNode(e.delta);
                }

                GUI.DragWindow();
            }
        }

        //The comments of the node sitting next or bottom of it
        void DrawNodeComments()
        {
            if (!string.IsNullOrEmpty(nodeComment) && graph && graph.showComments)
            {
                var commentsRect = new Rect();
                var size         = new GUIStyle("textArea").CalcSize(new GUIContent(nodeComment));

                if (outConnections.Count == 0)
                {
                    size.y       = new GUIStyle("textArea").CalcHeight(new GUIContent(nodeComment), nodeRect.width);
                    commentsRect = new Rect(nodeRect.x, nodeRect.yMax + 5, nodeRect.width, size.y);
                }
                else
                {
                    commentsRect = new Rect(nodeRect.xMax + 5, nodeRect.yMin, Mathf.Min(size.x, nodeRect.width), nodeRect.height);
                }

                GUI.color           = new Color(1, 1, 1, 0.6f);
                GUI.backgroundColor = new Color(1f, 1f, 1f, 0.2f);
                GUI.Box(commentsRect, nodeComment, "textArea");
                GUI.backgroundColor = Color.white;
                GUI.color           = Color.white;
            }
        }

        //Shows the tag label on the left of the node if it is tagged
        void DrawNodeTag()
        {
            if (!string.IsNullOrEmpty(tag))
            {
                var size    = new GUIStyle("label").CalcSize(new GUIContent(tag));
                var tagRect = new Rect(nodeRect.x - size.x - 10, nodeRect.y, size.x, size.y);
                GUI.Label(tagRect, tag);
                tagRect.width  = 12;
                tagRect.height = 12;
                tagRect.y     += tagRect.height + 5;
                tagRect.x      = nodeRect.x - 22;
                GUI.DrawTexture(tagRect, EditorUtils.tagIcon);
            }
        }

        //Function to pan the node recursively
        void RecursivePanNode(Vector2 delta)
        {
            nodeRect.center += delta;

            for (int i = 0; i < outConnections.Count; i++)
            {
                var node = outConnections[i].targetNode;
                if (node.ID > this.ID)
                {
                    node.RecursivePanNode(delta);
                }
            }
        }

        //The inspector of the node shown in the editor panel or else.
        public void ShowNodeInspectorGUI()
        {
            Undo.RecordObject(this, "Node Inspector");
            if (NCPrefs.showNodeInfo)
            {
                GUI.backgroundColor = new Color(0.8f, 0.8f, 1);
                EditorGUILayout.HelpBox(nodeDescription, MessageType.None);
                GUI.backgroundColor = Color.white;
            }

            GUILayout.BeginHorizontal();
            if (!inIconMode && allowAsPrime)
            {
                customName = EditorGUILayout.TextField(customName);
                EditorUtils.TextFieldComment(customName, "Name...");
            }

            tag = EditorGUILayout.TextField(tag);
            EditorUtils.TextFieldComment(tag, "Tag...");

            GUILayout.EndHorizontal();

            nodeComment = EditorGUILayout.TextField(nodeComment);
            EditorUtils.TextFieldComment(nodeComment);

            EditorUtils.Separator();
            OnNodeInspectorGUI();
            TaskAssignableGUI();

            if (GUI.changed)
            {
                EditorUtility.SetDirty(this);
            }
        }

        void TaskAssignableGUI()
        {
            if (this is ITaskAssignable)
            {
                System.Type taskType = null;
                foreach (System.Type iType in this.GetType().GetInterfaces())
                {
                    if (iType.IsGenericType && iType.GetGenericTypeDefinition() == typeof(ITaskAssignable <>))
                    {
                        taskType = iType.GetGenericArguments()[0];
                        break;
                    }
                }

                if (taskType != null)
                {
                    var    assignable = this as ITaskAssignable;
                    string missing    = MissingTask(assignable.serializedTask);
                    if (missing != null)
                    {
                        GUILayout.Label("Missing: " + missing);
                        if (GUILayout.Button("Remove Missing"))
                        {
                            DestroyImmediate(assignable.serializedTask, true);
                            assignable.task = null;
                        }
                        return;
                    }

                    if (assignable.task == null)
                    {
                        EditorUtils.TaskSelectionButton(gameObject, taskType, delegate(Task t){ assignable.task = t; });
                    }
                    else
                    {
                        assignable.task.ShowInspectorGUI();
                    }
                }
            }
        }

        string MissingTask(Object o)
        {
            if (!Equals(o, null) && o.GetType() == typeof(Object) && o.ToString() != "null")
            {
                var s = o.ToString();
                s = s.Replace(gameObject.name + " ", "");
                return(string.Format("<color=#ff6457>* {0} *</color>", s));
            }
            return(null);
        }
        void OnEnable()
        {
            ProCamera2DEditorHelper.AssignProCamera2D(target as BasePC2D);

            _proCamera2DParallax = (ProCamera2DParallax)target;

            _proCamera2D = _proCamera2DParallax.ProCamera2D;

            _script = MonoScript.FromMonoBehaviour(_proCamera2DParallax);

            // Parallax layers List
            _parallaxLayersList = new ReorderableList(serializedObject, serializedObject.FindProperty("ParallaxLayers"), false, true, true, true);

            // Draw element callback
            _parallaxLayersList.drawElementCallback = (rect, index, isActive, isFocused) =>
            {
                rect.y += 2;
                var element = _parallaxLayersList.serializedProperty.GetArrayElementAtIndex(index);

                #if UNITY_5
                EditorGUI.PrefixLabel(new Rect(rect.x, rect.y, 65, 10), new GUIContent("Camera", "The parallax camera"), EditorStyles.boldLabel);
                #else
                EditorGUI.PrefixLabel(new Rect(rect.x, rect.y, 65, 10), new GUIContent("Camera", "The parallax camera"));
                #endif
                EditorGUI.PropertyField(new Rect(
                                            rect.x + 65,
                                            rect.y,
                                            80,
                                            EditorGUIUtility.singleLineHeight),
                                        element.FindPropertyRelative("ParallaxCamera"), GUIContent.none);


                // Speed slider
                #if UNITY_5
                EditorGUI.PrefixLabel(new Rect(rect.x + 170, rect.y, 65, 10), new GUIContent("Speed", "The relative speed at which the camera should move in comparison to the main camera."), EditorStyles.boldLabel);
                #else
                EditorGUI.PrefixLabel(new Rect(rect.x + 170, rect.y, 65, 10), new GUIContent("Speed", "The relative speed at which the camera should move in comparison to the main camera."));
                #endif
                EditorGUI.PropertyField(new Rect(
                                            rect.x + 210,
                                            rect.y,
                                            rect.width - 210,
                                            EditorGUIUtility.singleLineHeight),
                                        element.FindPropertyRelative("Speed"), GUIContent.none);


                // Layer mask
                #if UNITY_5
                EditorGUI.PrefixLabel(new Rect(rect.x, rect.y + 25, 65, 10), new GUIContent("Culling Mask", "Which layers should this camera render?"), EditorStyles.boldLabel);
                #else
                EditorGUI.PrefixLabel(new Rect(rect.x, rect.y + 25, 65, 10), new GUIContent("Culling Mask", "Which layers should this camera render?"));
                #endif
                EditorGUI.PropertyField(new Rect(
                                            rect.x + 85,
                                            rect.y + 25,
                                            rect.width - 85,
                                            EditorGUIUtility.singleLineHeight),
                                        element.FindPropertyRelative("LayerMask"), GUIContent.none);
            };

            // Draw header callback
            _parallaxLayersList.drawHeaderCallback = rect => EditorGUI.LabelField(rect, "Parallax layers");

            // Add element callback
            _parallaxLayersList.onAddCallback = list => AddParallaxLayer();

            // Remove element callback
            _parallaxLayersList.onRemoveCallback = list =>
            {
                if (EditorUtility.DisplayDialog("Warning!", "Are you sure you want to delete this layer?", "Yes", "No"))
                {
                    var cam = list.serializedProperty.GetArrayElementAtIndex(list.index).FindPropertyRelative("ParallaxCamera").objectReferenceValue as Camera;
                    if (cam != null)
                    {
                        DestroyImmediate(cam.gameObject);
                    }

                    ReorderableList.defaultBehaviours.DoRemoveButton(list);
                }
            };

            // Select element callback
            _parallaxLayersList.onSelectCallback = list =>
            {
                EditorGUIUtility.PingObject(list.serializedProperty.GetArrayElementAtIndex(list.index).FindPropertyRelative("ParallaxCamera").objectReferenceValue as Camera);
            };

            _parallaxLayersList.onReorderCallback = list =>
            {
                if (_proCamera2DParallax.ParallaxLayers[0].ParallaxCamera.clearFlags != CameraClearFlags.SolidColor &&
                    _proCamera2DParallax.ParallaxLayers[0].ParallaxCamera.clearFlags != CameraClearFlags.Skybox)
                {
                    _proCamera2DParallax.ParallaxLayers[0].ParallaxCamera.clearFlags = CameraClearFlags.SolidColor;
                }
            };

            _parallaxLayersList.elementHeight = 65;
            _parallaxLayersList.headerHeight  = 18;
            _parallaxLayersList.draggable     = true;
        }
Exemplo n.º 18
0
        void OnEnable()
        {
            ProCamera2DEditorHelper.AssignProCamera2D(target as BasePC2D);

            _script = MonoScript.FromMonoBehaviour((ProCamera2DLimitDistance)target);
        }
Exemplo n.º 19
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            EditorGUI.BeginProperty(position, label, property);

            // Lumos: check type and attribute, and use defaults if none are present.
            var propertyObject = GetTargetObjectOfProperty(property);
            var isAttribute    = attribute is DrawInlineAttribute &&
                                 (propertyObject is ScriptableObject || propertyObject is null);
            var isInline = propertyObject is InlineScriptableObject || propertyObject is null;

            if (!isAttribute && !isInline)
            {
                EditorGUI.LabelField(position, "Error: Must derive from (Inline)ScriptableObject");
                EditorGUI.EndProperty();
                return;
            }

            var attr = isAttribute ? (DrawInlineAttribute)attribute : new DrawInlineAttribute();

            var lineHeight = EditorGUIUtility.singleLineHeight;
            var labelW     = EditorGUIUtility.labelWidth;
            var vertSep    = EditorGUIUtility.standardVerticalSpacing;

            // When unassigned, show a "Create" button and allow assignment
            if (property.objectReferenceValue == null)
            {
                var nameLabel = attr.showName
                    ? string.IsNullOrEmpty(attr.nameOverride) ? null : new GUIContent(attr.nameOverride)
                    : GUIContent.none;
                EditorGUI.ObjectField(new Rect(position.x, position.y, position.width - 60, lineHeight),
                                      property, nameLabel);

                if (GUI.Button(new Rect(position.x + position.width - 58, position.y, 58, lineHeight), "Create"))
                {
                    var selectedAssetPath = "Assets";
                    var targetObj         = property.serializedObject.targetObject;
                    if (targetObj is MonoBehaviour || targetObj is ScriptableObject)
                    {
                        var scriptFile = targetObj is MonoBehaviour obj
                            ? MonoScript.FromMonoBehaviour(obj)
                            : MonoScript.FromScriptableObject(targetObj as ScriptableObject);

                        selectedAssetPath = System.IO.Path.GetDirectoryName(AssetDatabase.GetAssetPath(scriptFile));
                    }

                    var type = fieldInfo.FieldType;
                    if (type.IsArray)
                    {
                        type = type.GetElementType();
                    }
                    else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List <>))
                    {
                        type = type.GetGenericArguments()[0];
                    }
                    property.objectReferenceValue = CreateAssetWithSavePrompt(type, selectedAssetPath);
                }
            }
            // Otherwise, make foldouts and so on.
            else
            {
                // Lumos: This isn't how you make a foldout. By making a labelled foldout and then adjusting the width
                // of the property fields, you're making the field more indented than when there's no object assigned...
                // The initial version of this whole thing is also an example of bad design: sure, it works in the one
                // use case it's been tested in, but relying on x = 0 and screen.width completely breaks this when
                // it's being nested in other stuff, for instance.

                // This is the only information the foldout needs if you're making a field anyway.
                var foldoutRect = new Rect(position.x, position.y, labelW, lineHeight);
                property.isExpanded = AnyPropertyVisible(property) &&
                                      EditorGUI.Foldout(foldoutRect, property.isExpanded, "", true);

                var propRect  = new Rect(position.x, position.y, position.width, lineHeight);
                var labelName = attr.showName
                    ? string.IsNullOrEmpty(attr.nameOverride) ? null : new GUIContent(attr.nameOverride)
                    : GUIContent.none;
                EditorGUI.PropertyField(propRect, property, labelName, true);

                if (GUI.changed)
                {
                    property.serializedObject.ApplyModifiedProperties();
                }
                if (property.objectReferenceValue == null)
                {
                    GUIUtility.ExitGUI();
                }

                if (property.isExpanded)
                {
                    var baseHeight = GetPropertyHeight(property, label); // Lumos: position.height is unreliable when nested
                    // Draw a background that shows us clearly which fields are part of the ScriptableObject
                    var boxRect = new Rect(position.x - 4, position.y + lineHeight + vertSep - 1, position.width + 8,
                                           baseHeight - lineHeight - vertSep - 1);
                    GUI.Box(boxRect, "");

                    EditorGUI.indentLevel++;
                    var data             = (ScriptableObject)property.objectReferenceValue;
                    var serializedObject = new SerializedObject(data);

                    // Iterate over all the values and draw them
                    var prop = serializedObject.GetIterator();
                    var y    = position.y + lineHeight + vertSep * 2;
                    if (prop.NextVisible(true))
                    {
                        do
                        {
                            // Don't bother drawing the class file
                            if (prop.name == "m_Script")
                            {
                                continue;
                            }
                            var height = EditorGUI.GetPropertyHeight(prop, new GUIContent(prop.displayName), true);
                            EditorGUI.PropertyField(new Rect(position.x, y, position.width, height), prop, true);
                            y += height + vertSep;
                        } while (prop.NextVisible(false));
                    }

                    if (GUI.changed)
                    {
                        serializedObject.ApplyModifiedProperties();
                    }

                    EditorGUI.indentLevel--;
                }
            }

            property.serializedObject.ApplyModifiedProperties();
            EditorGUI.EndProperty();
        }
Exemplo n.º 20
0
 public static UdonSharpProgramAsset GetUdonSharpProgramAsset(UdonSharpBehaviour udonSharpBehaviour)
 {
     return(GetUdonSharpProgramAsset(MonoScript.FromMonoBehaviour(udonSharpBehaviour)));
 }
Exemplo n.º 21
0
        public void Draw(MonoBehaviour monoBehaviour)
        {
            if (mcsCavesIcon == null || deIcon == null)
            {
                string path = AssetDatabase.GetAssetPath(MonoScript.FromMonoBehaviour(monoBehaviour)).Replace("Scripts/Mesh/MeshCombiner.cs", "Products/");
                mcsIcon      = AssetDatabase.LoadAssetAtPath(path + "MCSIcon.jpg", typeof(Texture)) as Texture;
                mcsCavesIcon = AssetDatabase.LoadAssetAtPath(path + "MCSCavesIcon.jpg", typeof(Texture)) as Texture;
                deIcon       = AssetDatabase.LoadAssetAtPath(path + "deIcon.jpg", typeof(Texture)) as Texture;
                tcIcon       = AssetDatabase.LoadAssetAtPath(path + "tcIcon.jpg", typeof(Texture)) as Texture;
                wcIcon       = AssetDatabase.LoadAssetAtPath(path + "wcIcon.jpg", typeof(Texture)) as Texture;
            }

            Rect rect1 = GUILayoutUtility.GetLastRect();

            Rect rect = new Rect(rect1.x, rect1.y, 128, 128);

            rect.x += 4;
            rect.y += 2;
            rect.x -= scrollBarX;
            float width = rect.width + 4;

            float found = 0;

            // Debug.Log(Screen.width + " " + (width * 4));

            if (!mcsInProject)
            {
                if (GUI.Button(rect, new GUIContent(string.Empty, mcsIcon, "50% Discount on Unity's Super Sale NOW!\nFrom $45 only for $22.50!\n\nClick to go to 'Mesh Combine Studio 2'.\n\nMesh Combine Studio is an automatic grid cell based mesh combiner which can dramatically improve the performance of your game. MCS can give up to 20x better performance compared to Unity’s static batching, while giving a more smooth and stable FPS.\n\nWe use MCS grid cell based combining in our game DRONE for the modular building in our arena editor and pre - made arenas, without MCS our game wouldn't run.\n\nInstead of manually combining meshes, which is very tedious, MCS will do this automatically for you sorted in grid cells, and the performance improvements it gives cannot be achieved with manual combining. Just simply drag and drop a MCS prefab in your Scene and tweak the many available conditions to your specific needs and you are ready to go.")))
                {
                    Application.OpenURL("https://assetstore.unity.com/packages/tools/modeling/mesh-combine-studio-2-101956?aid=1011le9dK&utm_source=aff");
                }
                rect.x += width;
                found++;
            }
            if (!mcsCavesInProject)
            {
                if (GUI.Button(rect, new GUIContent(string.Empty, mcsCavesIcon, "Click to go to 'MCS Caves & Overhangs' Extension.\n\nThis 'Mesh Combine Studio 2' extension gives the best performance possible by using the easiest way to get amazing looking Caves and Overhangs on any terrain solution.\n\nYou can use any Rock Asset pack from the Unity Asset Store and stack them together to create caves and overhangs, and this extension will combine all rocks and remove all inside polygons that are never visible. Resulting in a ~60-80% polygon removal + combining which gives unbeatable performance and lightmap texture reduction.\n\nOur arenas in DRONE are optimized with this MCS extension. It can also be used on any other kind of closed meshes like a level consisting out of snapped cubes.")))
                {
                    Application.OpenURL("https://assetstore.unity.com/packages/tools/terrain/mcs-caves-overhangs-144413?aid=1011le9dK");
                }
                rect.x += width;
                found++;
            }
            if (!deInProject)
            {
                if (GUI.Button(rect, new GUIContent(string.Empty, deIcon, "50% Discount on Unity's Super Sale NOW!\nFrom $35 only for $17.50!\n\nClick to go to 'Debugging Essentials'.\n\nDebugging Essentials contains 5 crucial tools which will save you tons of time needed for coding while avoiding debugging headaches, making developing a lot more enjoyable!\n\n* Runtime Hierarchy.\n* Runtime Deep Inspector.\n* Runtime Camera Navigation.\n* Runtime Console.\n* HTML Debug Logs.")))
                {
                    Application.OpenURL("https://assetstore.unity.com/packages/tools/utilities/debugging-essentials-170773?aid=1011le9dK");
                }
                rect.x += width;
                found++;
            }
            if (!tcInProject)
            {
                if (GUI.Button(rect, new GUIContent(string.Empty, tcIcon, "Click to go to 'Terrain Composer 2'.\n\nTerrainComposer2 is a powerful node based multi-terrain tile generator. TC2 makes use of the latest GPU technology to give you instant real-time results, which makes creating terrains faster and more easy than ever before.\n\nTC2 its folder like layer system and workflow is similar to that of Photoshop, which makes it possible to have full control and make quick changes any time during the workflow.")))
                {
                    Application.OpenURL("https://assetstore.unity.com/packages/tools/terrain/terrain-composer-2-65563?aid=1011le9dK");
                }
                rect.x += width;
                found++;
            }
            if (!wcInProject)
            {
                if (GUI.Button(rect, new GUIContent(string.Empty, wcIcon, "50% Discount on Unity's Super Sale NOW!\nFrom $45 only for $22.50!\n\nClick to go to 'World Composer'.\n\nWorldComposer is a tool to extract heightmap data and satellite images from the real world. It uses Bing maps, like in the new Microsoft Flight Simulator 2020.\n\nWorldComposer can create terrains by itself, but the exported heightmaps(e.g. as stamps) and satellite images can also be used in other terrain tools like TerrainComposer 2, Gaia, WorldMachine, MapMapic, WorldCreator, etc.")))
                {
                    Application.OpenURL("https://assetstore.unity.com/packages/tools/terrain/world-composer-13238?aid=1011le9dK");
                }
                rect.x += width;
                found++;
            }

            float size = (128 * (found + 0.5f)) - Screen.width;

            if (found > 0)
            {
                GUILayout.Space(132);
                if (size > 0)
                {
                    scrollBarX = GUILayout.HorizontalScrollbar(scrollBarX, 25, 0, size);
                }
                DrawSpacer(0, 5, 0);
            }
        }
Exemplo n.º 22
0
        internal static UdonBehaviour[] ConvertToUdonBehavioursInternal(UdonSharpBehaviour[] components, bool shouldUndo, bool showPrompts)
        {
            components = components.Distinct().ToArray();

            bool convertChildren = true;

            if (showPrompts)
            {
                HashSet <UdonSharpBehaviour> allReferencedBehaviours = new HashSet <UdonSharpBehaviour>();

                // Check if any of these need child component conversion
                foreach (UdonSharpBehaviour targetObject in components)
                {
                    HashSet <UdonSharpBehaviour> referencedBehaviours = new HashSet <UdonSharpBehaviour>();

                    CollectUdonSharpBehaviourReferencesInternal(targetObject, referencedBehaviours);

                    if (referencedBehaviours.Count > 1)
                    {
                        foreach (UdonSharpBehaviour referencedBehaviour in referencedBehaviours)
                        {
                            if (referencedBehaviour != targetObject)
                            {
                                allReferencedBehaviours.Add(referencedBehaviour);
                            }
                        }
                    }
                }

                if (allReferencedBehaviours.Count > 0)
                {
                    // This is an absolute mess, it should probably just be simplified to counting the number of affected behaviours
                    string referencedBehaviourStr;
                    if (allReferencedBehaviours.Count <= 2)
                    {
                        referencedBehaviourStr = string.Join(", ", allReferencedBehaviours.Select(e => $"'{e.ToString()}'"));
                    }
                    else
                    {
                        referencedBehaviourStr = $"{allReferencedBehaviours.Count} behaviours";
                    }

                    string rootBehaviourStr;

                    if (components.Length <= 2)
                    {
                        rootBehaviourStr = $"{string.Join(", ", components.Select(e => $"'{e.ToString()}'"))} reference{(components.Length == 1 ? "s" : "")} ";
                    }
                    else
                    {
                        rootBehaviourStr = $"{components.Length} behaviours to convert reference ";
                    }

                    string messageStr = $"{rootBehaviourStr}{referencedBehaviourStr}. Do you want to convert all referenced behaviours as well? If no, references to these behaviours will be set to null.";

                    int result = EditorUtility.DisplayDialogComplex("Dependent behaviours found", messageStr, "Yes", "Cancel", "No");

                    if (result == 2) // No
                    {
                        convertChildren = false;
                    }
                    else if (result == 1) // Cancel
                    {
                        return(null);
                    }
                }
            }

            if (shouldUndo)
            {
                Undo.RegisterCompleteObjectUndo(components, "Convert to UdonBehaviour");
            }

            List <UdonBehaviour> createdComponents = new List <UdonBehaviour>();

            foreach (UdonSharpBehaviour targetObject in components)
            {
                MonoScript            behaviourScript = MonoScript.FromMonoBehaviour(targetObject);
                UdonSharpProgramAsset programAsset    = GetUdonSharpProgramAsset(behaviourScript);

                if (programAsset == null)
                {
                    if (showPrompts)
                    {
                        string scriptPath      = AssetDatabase.GetAssetPath(behaviourScript);
                        string scriptDirectory = Path.GetDirectoryName(scriptPath);
                        string scriptFileName  = Path.GetFileNameWithoutExtension(scriptPath);

                        string assetPath = Path.Combine(scriptDirectory, $"{scriptFileName}.asset").Replace('\\', '/');

                        if (EditorUtility.DisplayDialog("No linked program asset", $"There was no UdonSharpProgramAsset found for '{behaviourScript.GetClass()}', do you want to create one?", "Ok", "Cancel"))
                        {
                            if (AssetDatabase.LoadAssetAtPath <UdonSharpProgramAsset>(assetPath) != null)
                            {
                                if (!EditorUtility.DisplayDialog("Existing file found", $"Asset file {assetPath} already exists, do you want to overwrite it?", "Ok", "Cancel"))
                                {
                                    continue;
                                }
                            }
                        }
                        else
                        {
                            continue;
                        }

                        programAsset = ScriptableObject.CreateInstance <UdonSharpProgramAsset>();
                        programAsset.sourceCsScript = behaviourScript;
                        AssetDatabase.CreateAsset(programAsset, assetPath);
                        AssetDatabase.SaveAssets();

                        UdonSharpProgramAsset.ClearProgramAssetCache();

                        programAsset.CompileCsProgram();

                        AssetDatabase.SaveAssets();

                        AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
                    }
                    else
                    {
                        Debug.LogWarning($"Could not convert U# behaviour '{behaviourScript.GetClass()}' on '{targetObject.gameObject}' because it does not have a corresponding UdonSharpProgramAsset");
                        continue;
                    }
                }

                GameObject targetGameObject = targetObject.gameObject;

                UdonBehaviour udonBehaviour = null;

                if (shouldUndo)
                {
                    udonBehaviour = Undo.AddComponent <UdonBehaviour>(targetGameObject);
                }
                else
                {
                    udonBehaviour = targetGameObject.AddComponent <UdonBehaviour>();
                }

                udonBehaviour.programSource = programAsset;

                //if (shouldUndo)
                //    Undo.RegisterCompleteObjectUndo(targetObject, "Convert C# to U# behaviour");

                UdonSharpEditorUtility.SetBackingUdonBehaviour(targetObject, udonBehaviour);

                try
                {
                    if (convertChildren)
                    {
                        UdonSharpEditorUtility.CopyProxyToUdon(targetObject, shouldUndo ? ProxySerializationPolicy.AllWithCreateUndo : ProxySerializationPolicy.All);
                    }
                    else
                    {
                        UdonSharpEditorUtility.CopyProxyToUdon(targetObject, ProxySerializationPolicy.RootOnly);
                    }
                }
                catch (System.Exception e)
                {
                    Debug.LogError(e);
                }

                UdonSharpEditorUtility.SetBackingUdonBehaviour(targetObject, null);

                System.Type behaviourType = targetObject.GetType();

                UdonSharpBehaviour newProxy;

                if (shouldUndo)
                {
                    newProxy = (UdonSharpBehaviour)Undo.AddComponent(targetObject.gameObject, behaviourType);
                }
                else
                {
                    newProxy = (UdonSharpBehaviour)targetObject.gameObject.AddComponent(behaviourType);
                }

                UdonSharpEditorUtility.SetBackingUdonBehaviour(newProxy, udonBehaviour);
                try
                {
                    UdonSharpEditorUtility.CopyUdonToProxy(newProxy);
                }
                catch (System.Exception e)
                {
                    Debug.LogError(e);
                }

                if (shouldUndo)
                {
                    Undo.DestroyObjectImmediate(targetObject);
                }
                else
                {
                    Object.DestroyImmediate(targetObject);
                }

                newProxy.hideFlags = HideFlags.DontSaveInBuild |
#if !UDONSHARP_DEBUG
                                     HideFlags.HideInInspector |
#endif
                                     HideFlags.DontSaveInEditor;

                newProxy.enabled = false;

                createdComponents.Add(udonBehaviour);
            }

            return(createdComponents.ToArray());
        }
Exemplo n.º 23
0
        public override void OnInspectorGUI()
        {
            // Manually recreate the inspector so we can add the event foldout:
            GUI.enabled = false;
            EditorGUILayout.ObjectField("Script", MonoScript.FromMonoBehaviour((TurnOnXR)target), typeof(TurnOnXR), false);
            GUI.enabled = true;

            serializedObject.Update();

            EditorGUILayout.PropertyField(lifecycleTrigger, new GUIContent("Initialize On"));

            showEvents = EditorGUILayout.Foldout(showEvents, "Completion Events");
            if (showEvents)
            {
                EditorGUILayout.PropertyField(onSuccess);
                EditorGUILayout.PropertyField(onFailure);
            }

            showDebug = EditorGUILayout.Foldout(showDebug, "Developer Controls");
            if (showDebug)
            {
                EditorGUILayout.PropertyField(forceFailure);
                EditorGUILayout.PropertyField(log);
            }

            serializedObject.ApplyModifiedProperties();

            // Custom helpboxes:

            if (forceFailure.boolValue == true)
            {
                EditorGUILayout.HelpBox("This script has ForceFailure enabled. Don't forget to turn that off if it isn't intended!", MessageType.Error);
            }

            var origTargetGroup = BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget);

            if (UnityEditorInternal.VR.VREditor.GetVREnabledOnTargetGroup(origTargetGroup) == false)
            {
                EditorGUILayout.HelpBox("XR support is disabled in this project! You can change this in Project Settings > Player > XR Settings.", MessageType.Error);
                if (GUILayout.Button("Fix it!\n(Enable XR support)"))
                {
                    UnityEditorInternal.VR.VREditor.SetVREnabledOnTargetGroup(origTargetGroup, true);
                }
            }

            if (XRSettings.supportedDevices.Length == 0 || (XRSettings.supportedDevices.Length == 1 && XRSettings.supportedDevices[0] == "None"))
            {
                EditorGUILayout.HelpBox("You have no XR devices supported in Project Settings > Player > XR Settings. This script will do nothing.", MessageType.Error);
            }

            if (XRSettings.supportedDevices.Length > 0 && XRSettings.supportedDevices[0] != "None")
            {
                EditorGUILayout.HelpBox("This script works best when the first supported XR device is `none`. You can change this in Project Settings > Player > XR Settings.", MessageType.Warning);
                if (GUILayout.Button("Fix it!\n(Add `None` to supportedDevices)"))
                {
                    List <string> devices = new List <string>(XRSettings.supportedDevices);
                    // Just in case it wasn't in the first position.
                    devices.Remove("None");
                    devices.Insert(0, "None");
                    UnityEditorInternal.VR.VREditor.SetVREnabledDevicesOnTargetGroup(origTargetGroup, devices.ToArray());
                }
            }
        }
Exemplo n.º 24
0
        void OnEnable()
        {
            if (target == null)
            {
                return;
            }

            ProCamera2DEditorHelper.AssignProCamera2D(target as BasePC2D);

            var proCamera2DShake = (ProCamera2DShake)target;

            _script = MonoScript.FromMonoBehaviour(proCamera2DShake);

            //
            // ShakePresets list
            //
            _shakePresetsList = new ReorderableList(serializedObject, serializedObject.FindProperty("ShakePresets"), true, true, true, true);

            _shakePresetsList.drawElementCallback = (rect, index, isActive, isFocused) =>
            {
                rect.y += 2;
                var element = _shakePresetsList.serializedProperty.GetArrayElementAtIndex(index);

                if (element == null || element.objectReferenceValue == null)
                {
                    proCamera2DShake.ShakePresets.RemoveAt(index);
                    return;
                }

                // Name field
                EditorGUI.LabelField(
                    new Rect(
                        rect.x,
                        rect.y,
                        rect.width / 2f,
                        EditorGUIUtility.singleLineHeight * 1.1f),
                    ((ShakePreset)element.objectReferenceValue).name);

                // Edit button
                if (GUI.Button(new Rect(
                                   rect.x + 2 * rect.width / 4f + 5,
                                   rect.y - 2,
                                   rect.width / 4f - 5,
                                   EditorGUIUtility.singleLineHeight * 1.1f), "Edit"))
                {
                    Selection.activeObject = (ShakePreset)element.objectReferenceValue;
                }

                // Shake button
                GUI.enabled = Application.isPlaying;
                if (GUI.Button(new Rect(
                                   rect.x + 3 * rect.width / 4f + 5,
                                   rect.y - 2,
                                   rect.width / 4f - 5,
                                   EditorGUIUtility.singleLineHeight * 1.1f), "Shake!"))
                {
                    proCamera2DShake.Shake((ShakePreset)element.objectReferenceValue);
                }
                GUI.enabled = true;
            };

            _shakePresetsList.onAddCallback = (list) =>
            {
                _currentPickerWindow = GUIUtility.GetControlID(FocusType.Passive) + 100;
                EditorGUIUtility.ShowObjectPicker <ShakePreset>(null, false, "", _currentPickerWindow);
            };

            _shakePresetsList.onSelectCallback = (list) =>
            {
                var element = _shakePresetsList.serializedProperty.GetArrayElementAtIndex(list.index);

                if (element != null)
                {
                    EditorGUIUtility.PingObject(element.objectReferenceValue);
                }
            };

            _shakePresetsList.onRemoveCallback = (list) =>
            {
                var element = _shakePresetsList.serializedProperty.GetArrayElementAtIndex(list.index);

                proCamera2DShake.ShakePresets.Remove((ShakePreset)element.objectReferenceValue);
            };

            _shakePresetsList.drawHeaderCallback = (Rect rect) =>
            {
                EditorGUI.LabelField(rect, "Shake Presets");
            };


            //
            // ConstantShakePresets list
            //

            _constantShakePresetsList = new ReorderableList(serializedObject, serializedObject.FindProperty("ConstantShakePresets"), true, true, true, true);

            _constantShakePresetsList.drawElementCallback = (rect, index, isActive, isFocused) =>
            {
                rect.y += 2;
                var element = _constantShakePresetsList.serializedProperty.GetArrayElementAtIndex(index);

                if (element == null || element.objectReferenceValue == null)
                {
                    proCamera2DShake.ConstantShakePresets.RemoveAt(index);
                    return;
                }

                var preset = (ConstantShakePreset)element.objectReferenceValue;

                // Name field
                EditorGUI.LabelField(
                    new Rect(
                        rect.x,
                        rect.y,
                        rect.width / 2f,
                        EditorGUIUtility.singleLineHeight * 1.1f),
                    (preset).name);

                // Toggle to enable on start
                if (!Application.isPlaying)
                {
                    if (GUI.Toggle(new Rect(
                                       rect.x + 1 * rect.width / 4f + 5,
                                       rect.y - 2,
                                       rect.width / 4f - 5,
                                       EditorGUIUtility.singleLineHeight * 1.1f),
                                   proCamera2DShake.StartConstantShakePreset == preset,
                                   "Enable on Start"))
                    {
                        if (Event.current.type == EventType.Used && EditorApplication.timeSinceStartup - _toggleButtonClick > .5)
                        {
                            if (proCamera2DShake.StartConstantShakePreset == preset)
                            {
                                proCamera2DShake.StartConstantShakePreset = null;
                            }
                            else
                            {
                                proCamera2DShake.StartConstantShakePreset = preset;
                            }

                            _toggleButtonClick = EditorApplication.timeSinceStartup;
                        }
                    }
                }

                // Edit button
                if (GUI.Button(new Rect(
                                   rect.x + 2 * rect.width / 4f + 5,
                                   rect.y - 2,
                                   rect.width / 4f - 5,
                                   EditorGUIUtility.singleLineHeight * 1.1f), "Edit"))
                {
                    Selection.activeObject = preset;
                }

                // Shake button
                GUI.enabled = Application.isPlaying;
                if (GUI.Button(new Rect(
                                   rect.x + 3 * rect.width / 4f + 5,
                                   rect.y - 2,
                                   rect.width / 4f - 5,
                                   EditorGUIUtility.singleLineHeight * 1.1f), (proCamera2DShake.CurrentConstantShakePreset != null && proCamera2DShake.CurrentConstantShakePreset.GetInstanceID() == preset.GetInstanceID()) ? "Disable" : "Enable"))
                {
                    if (proCamera2DShake.CurrentConstantShakePreset == null || proCamera2DShake.CurrentConstantShakePreset.GetInstanceID() != preset.GetInstanceID())
                    {
                        proCamera2DShake.ConstantShake(preset);
                    }
                    else
                    {
                        proCamera2DShake.StopConstantShaking();
                    }
                }
                GUI.enabled = true;
            };

            _constantShakePresetsList.onAddCallback = (list) =>
            {
                _currentPickerWindow = GUIUtility.GetControlID(FocusType.Passive) + 100;
                EditorGUIUtility.ShowObjectPicker <ConstantShakePreset>(null, false, "", _currentPickerWindow);
            };

            _constantShakePresetsList.onSelectCallback = (list) =>
            {
                var element = _constantShakePresetsList.serializedProperty.GetArrayElementAtIndex(list.index);

                if (element != null)
                {
                    EditorGUIUtility.PingObject(element.objectReferenceValue);
                }
            };

            _constantShakePresetsList.onRemoveCallback = (list) =>
            {
                var element = _constantShakePresetsList.serializedProperty.GetArrayElementAtIndex(list.index);

                proCamera2DShake.ConstantShakePresets.Remove((ConstantShakePreset)element.objectReferenceValue);
            };

            _constantShakePresetsList.drawHeaderCallback = (Rect rect) =>
            {
                EditorGUI.LabelField(rect, "Constant Shake Presets");
            };
        }
Exemplo n.º 25
0
        /// <summary>
        /// Get relative to Assets folder path to script file location
        /// </summary>
        public static string GetRelativeScriptAssetsPath(MonoBehaviour mb)
        {
            MonoScript ms = MonoScript.FromMonoBehaviour(mb);

            return(AssetDatabase.GetAssetPath(ms));
        }
Exemplo n.º 26
0
    public override void OnInspectorGUI()
    {
        var myScript        = target as PathAnimator;
        SerializedObject so = new SerializedObject(target);

        // Script Field
        GUI.enabled = false;
        EditorGUILayout.ObjectField("Script", MonoScript.FromMonoBehaviour((PathAnimator)target), typeof(PathAnimator), false);
        GUI.enabled = true;

        SerializedProperty component_with_vertex_path = so.FindProperty("component_with_vertex_path");

        EditorGUILayout.PropertyField(component_with_vertex_path, true); // True means show children

        SerializedProperty path_generator = so.FindProperty("path_generator");

        EditorGUILayout.PropertyField(path_generator, true); // True means show children

        if (GUILayout.Button("Switch Control Mode"))
        {
            is_speed_control = !is_speed_control;
            Debug.Log(is_speed_control);
        }

        SerializedProperty speed_curve = so.FindProperty("speed_curve");

        EditorGUILayout.PropertyField(speed_curve, true); // True means show children

        SerializedProperty speed_coeff = so.FindProperty("speed_coeff");
        SerializedProperty period      = so.FindProperty("period");

        if (is_speed_control)
        {
            EditorGUILayout.PropertyField(speed_coeff, true); // True means show children
            EditorGUILayout.LabelField("Period: ", period.floatValue.ToString());

            if (speed_coeff.floatValue <= 0.0f)
            {
                speed_coeff.floatValue = 0.01f;
            }

            period.floatValue = myScript.CalcPeriod(0.01f, speed_coeff.floatValue);
        }
        else
        {
            EditorGUILayout.LabelField("Speed Coefficient: ", speed_coeff.floatValue.ToString());
            EditorGUILayout.PropertyField(period, true); // True means show children

            if (period.floatValue <= 0.0f)
            {
                period.floatValue = 0.01f;
            }

            speed_coeff.floatValue = myScript.CalcSpeedCoeff(0.01f, period.floatValue);
        }

        SerializedProperty MoveInWorldCoordinates = so.FindProperty("MoveInWorldCoordinates");

        EditorGUILayout.PropertyField(MoveInWorldCoordinates, true); // True means show children

        SerializedProperty min_speed = so.FindProperty("min_speed");

        EditorGUILayout.PropertyField(min_speed, true); // True means show children

        SerializedProperty stop_fraction = so.FindProperty("stop_fraction");

        EditorGUILayout.PropertyField(stop_fraction, true); // True means show children

        SerializedProperty end_of_path_instruction = so.FindProperty("end_of_path_instruction");

        EditorGUILayout.PropertyField(end_of_path_instruction, true); // True means show children

        SerializedProperty gradual_stop_length = so.FindProperty("gradual_stop_length");

        EditorGUILayout.PropertyField(gradual_stop_length, true); // True means show children

        SerializedProperty OnStart = so.FindProperty("OnStart");

        EditorGUILayout.PropertyField(OnStart, true); // True means show children

        SerializedProperty OnFixedUpdate = so.FindProperty("OnFixedUpdate");

        EditorGUILayout.PropertyField(OnFixedUpdate, true); // True means show children

        SerializedProperty OnFixedUpdateAnim = so.FindProperty("OnFixedUpdateAnim");

        EditorGUILayout.PropertyField(OnFixedUpdateAnim, true); // True means show children

        SerializedProperty OnPathEnd = so.FindProperty("OnPathEnd");

        EditorGUILayout.PropertyField(OnPathEnd, true); // True means show children

        so.ApplyModifiedProperties();                   // Remember to apply modified properties
    }
Exemplo n.º 27
0
    public override void OnInspectorGUI()
    {
        MeshCombiner meshCombiner = (MeshCombiner)target;
        Mesh         mesh         = meshCombiner.GetComponent <MeshFilter>().sharedMesh;

        #region Script:
        GUI.enabled = false;
        EditorGUILayout.ObjectField("Script", MonoScript.FromMonoBehaviour((MeshCombiner)target), typeof(MeshCombiner), false);
        GUI.enabled = true;
        #endregion Script.

        #region MeshFiltersToSkip array:
        SerializedProperty meshFiltersToSkip = serializedObject.FindProperty("meshFiltersToSkip");
        EditorGUI.BeginChangeCheck();
        EditorGUILayout.PropertyField(meshFiltersToSkip, true);
        if (EditorGUI.EndChangeCheck())
        {
            serializedObject.ApplyModifiedProperties();
        }
        #endregion MeshFiltersToSkip array.

        #region Button which combine Meshes into one Mesh & Toggles with combine options:
        // Button:
        if (GUILayout.Button("Combine Meshes"))
        {
            meshCombiner.CombineMeshes(true);
        }

        // Toggles:
        meshCombiner.CreateMultiMaterialMesh = GUILayout.Toggle(meshCombiner.CreateMultiMaterialMesh, "Create Multi-Material Mesh");
        meshCombiner.CombineInactiveChildren = GUILayout.Toggle(meshCombiner.CombineInactiveChildren, "Combine Inactive Children");

        meshCombiner.DeactivateCombinedChildren = GUILayout.Toggle(meshCombiner.DeactivateCombinedChildren, "Deactivate Combined Children");
        meshCombiner.DeactivateCombinedChildrenMeshRenderers = GUILayout.Toggle(meshCombiner.DeactivateCombinedChildrenMeshRenderers,
                                                                                "Deactivate Combined Children's MeshRenderers");

        // The last (5) "Destroy Combined Children" Toggle:
        GUIStyle style = new GUIStyle(EditorStyles.toggle);
        if (meshCombiner.DestroyCombinedChildren)
        {
            style.onNormal.textColor = new Color(1, 0.15f, 0);
        }
        meshCombiner.DestroyCombinedChildren = GUILayout.Toggle(meshCombiner.DestroyCombinedChildren,
                                                                new GUIContent("Destroy Combined Children", "In the editor this operation can NOT be undone!\n\n" +
                                                                               "If you want to bring back destroyed GameObjects, you have to load again the scene without saving."), style);
        #endregion Button which combine Meshes into one Mesh & Toggles with combine options.

        #region Path to the folder where combined Meshes will be saved:
        // Create Labels:
        GUILayout.Label("");
        GUILayout.Label(new GUIContent("Folder path:", "Folder path to save combined Mesh."));

        // Create style wherein text color will be red if folder path is not valid:
        style = new GUIStyle(EditorStyles.textField);
        bool isValidPath = IsValidPath(meshCombiner.FolderPath);
        if (!isValidPath)
        {
            style.normal.textColor  = Color.red;
            style.focused.textColor = Color.red;
        }

        // Create TextField with custom style:
        meshCombiner.FolderPath = EditorGUILayout.TextField(meshCombiner.FolderPath, style);
        #endregion Path to the folder where combined Meshes will be saved.

        #region Button which save/show combined Mesh:
        bool meshIsSaved = (mesh != null && AssetDatabase.Contains(mesh));
        GUI.enabled = (mesh != null && (isValidPath || meshIsSaved));         // Valid path is required for not saved Mesh.
        string saveMeshButtonText = (meshIsSaved) ? "Show Saved Combined Mesh" : "Save Combined Mesh";

        if (GUILayout.Button(saveMeshButtonText))
        {
            meshCombiner.FolderPath = SaveCombinedMesh(mesh, meshCombiner.FolderPath);
        }
        GUI.enabled = true;
        #endregion Button which save/show combined Mesh.
    }
        public override void OnInspectorGUI()
        {
            var obj = target as LocalizeStringResource;

            serializedObject.Update();

            EditorGUI.BeginDisabledGroup(true);
            EditorGUILayout.ObjectField("Script", MonoScript.FromMonoBehaviour((MonoBehaviour)target), typeof(MonoScript), false);
            EditorGUI.EndDisabledGroup();

            bool edited = false;

            EditorGUI.BeginChangeCheck();
            EditorGUILayout.PropertyField(items, itemsLabel, true);
            edited |= EditorGUI.EndChangeCheck();

            GUILayout.Space(15);

            if (items.arraySize > 0)
            {
                if (!string.IsNullOrEmpty(emptyIndexError))
                {
                    EditorGUILayout.HelpBox("There is empty ID (index) : " + emptyIndexError, MessageType.Error);
                }
                if (!string.IsNullOrEmpty(duplicateIDError))
                {
                    EditorGUILayout.HelpBox("There is duplicate ID : " + duplicateIDError, MessageType.Error);
                }
            }

            if (!Application.isPlaying)
            {
                if (obj.EditExecuting)
                {
                    return;
                }

                GUILayout.Space(15);
                //GUILayout.Box("Editor Tools", GUILayout.ExpandWidth(true), GUILayout.Height(20));

                insertIndex = EditorGUILayout.IntField("Insert Index", insertIndex);
                if (GUILayout.Button("Insert New Item"))
                {
                    if (obj.IsValidIndex(insertIndex))
                    {
                        Undo.RecordObject(target, "Insert New LocalizeString Item");
                    }
                    edited |= obj.InsetItem(insertIndex);
                }

                removeIndex = EditorGUILayout.IntField("Remove Index", removeIndex);
                if (GUILayout.Button("Remove Item"))
                {
                    if (obj.IsValidIndex(removeIndex))
                    {
                        Undo.RecordObject(target, "Remove LocalizeString Item");
                    }
                    edited |= obj.RemoveItem(removeIndex);
                }

                EditorGUI.BeginChangeCheck();
                searchID = EditorGUILayout.TextField("Search ID", searchID);
                if (EditorGUI.EndChangeCheck())
                {
                    if (!string.IsNullOrEmpty(searchID))
                    {
                        insertIndex = removeIndex = obj.FindIndex(searchID, true);
                    }
                    else
                    {
                        insertIndex = removeIndex = -1;
                    }
                }

                if (GUILayout.Button("Get Index from ID  (Whole match)"))
                {
                    insertIndex = removeIndex = obj.FindIndex(searchID);
                }
            }

            serializedObject.ApplyModifiedProperties();
            EditorUtility.SetDirty(target);

            //Check for ID errors
            if (edited)
            {
                CheckValidity();
            }
        }
Exemplo n.º 29
0
        void OnEnable()
        {
            ProCamera2DEditorHelper.AssignProCamera2D(target as BasePC2D);

            var proCamera2DRooms = (ProCamera2DRooms)target;

            // Add Numeric Boundaries component if needed
            var numericBoundaries = proCamera2DRooms.ProCamera2D.GetComponent <ProCamera2DNumericBoundaries>();

            if (numericBoundaries == null)
            {
                proCamera2DRooms.ProCamera2D.gameObject.AddComponent <ProCamera2DNumericBoundaries>();
            }

            // Create Vector conversion methods
            switch (proCamera2DRooms.ProCamera2D.Axis)
            {
            case MovementAxis.XY:
                Vector3H  = vector => vector.x;
                Vector3V  = vector => vector.y;
                VectorHVD = (h, v, d) => new Vector3(h, v, d);
                break;

            case MovementAxis.XZ:
                Vector3H  = vector => vector.x;
                Vector3V  = vector => vector.z;
                VectorHVD = (h, v, d) => new Vector3(h, d, v);
                break;

            case MovementAxis.YZ:
                Vector3H  = vector => vector.z;
                Vector3V  = vector => vector.y;
                VectorHVD = (h, v, d) => new Vector3(d, v, h);
                break;
            }

            // Script
            _script = MonoScript.FromMonoBehaviour(proCamera2DRooms);

            // Rooms List
            _roomsList = new ReorderableList(serializedObject, serializedObject.FindProperty("Rooms"), false, true, true, true);

            _roomsList.drawHeaderCallback = (Rect rect) =>
            {
                EditorGUI.LabelField(rect, "Rooms");
            };

            _roomsList.onSelectCallback = (list) =>
            {
                _currentlyEditingRoom = _roomsList.index;
                SceneView.RepaintAll();
            };

            _roomsList.onAddCallback = (list) =>
            {
                var index = list.serializedProperty.arraySize;
                list.serializedProperty.arraySize++;
                list.index = index;

                var newEntry = list.serializedProperty.GetArrayElementAtIndex(list.count - 1);
                if (list.count > 1)
                {
                    var prevRect = list.serializedProperty.GetArrayElementAtIndex(list.count - 2).FindPropertyRelative("Dimensions").rectValue;
                    prevRect.x += prevRect.width;
                    newEntry.FindPropertyRelative("Dimensions").rectValue = prevRect;
                }
                else if (list.count == 1)
                {
                    newEntry.FindPropertyRelative("Dimensions").rectValue          = new Rect(0, 0, 10, 10);
                    newEntry.FindPropertyRelative("TransitionDuration").floatValue = 1f;
                    newEntry.FindPropertyRelative("ZoomScale").floatValue          = 1.5f;
                }

                _currentlyEditingRoom = index;
            };

            _roomsList.onRemoveCallback = (list) =>
            {
                _currentlyEditingRoom = -1;
                SceneView.RepaintAll();
                ReorderableList.defaultBehaviours.DoRemoveButton(list);
            };

            _roomsList.drawElementCallback = (rect, index, isActive, isFocused) =>
            {
                rect.y += 2;
                var element = _roomsList.serializedProperty.GetArrayElementAtIndex(index);

                EditorGUI.DropShadowLabel(new Rect(rect.x, rect.y + 3, 60, 10), "Room " + index);
                rect.y += 20;

                #if UNITY_5_6_OR_NEWER
                EditorGUI.PrefixLabel(new Rect(rect.x, rect.y, 65, 10), new GUIContent("ID", "The room id"), EditorStyles.boldLabel);
                #else
                EditorGUI.PrefixLabel(new Rect(rect.x, rect.y, 65, 10), new GUIContent("ID", "The room id"));
                #endif
                EditorGUI.PropertyField(new Rect(
                                            rect.x + 80,
                                            rect.y,
                                            100,
                                            EditorGUIUtility.singleLineHeight),
                                        element.FindPropertyRelative("ID"), GUIContent.none);

                #if UNITY_5_6_OR_NEWER
                EditorGUI.PrefixLabel(new Rect(rect.x + 200, rect.y, 65, 10), new GUIContent("Rect", "The room size and position"), EditorStyles.boldLabel);
                #else
                EditorGUI.PrefixLabel(new Rect(rect.x + 200, rect.y, 65, 10), new GUIContent("Rect", "The room size and position"));
                #endif
                EditorGUI.PropertyField(new Rect(
                                            rect.x + 260,
                                            rect.y,
                                            rect.width - 260,
                                            EditorGUIUtility.singleLineHeight),
                                        element.FindPropertyRelative("Dimensions"), GUIContent.none);

                #if UNITY_5_6_OR_NEWER
                EditorGUI.PrefixLabel(new Rect(rect.x, rect.y + 45, 65, 10), new GUIContent("Ease Type", ""), EditorStyles.boldLabel);
                #else
                EditorGUI.PrefixLabel(new Rect(rect.x, rect.y + 45, 65, 10), new GUIContent("Ease Type", ""));
                #endif
                EditorGUI.PropertyField(new Rect(
                                            rect.x + 80,
                                            rect.y + 45,
                                            100,
                                            EditorGUIUtility.singleLineHeight),
                                        element.FindPropertyRelative("TransitionEaseType"), GUIContent.none);

                #if UNITY_5_6_OR_NEWER
                EditorGUI.PrefixLabel(new Rect(rect.x + 200, rect.y + 45, 65, 10), new GUIContent("Duration", "How long it takes for the camera to reach this room"), EditorStyles.boldLabel);
                #else
                EditorGUI.PrefixLabel(new Rect(rect.x + 200, rect.y + 45, 65, 10), new GUIContent("Duration", "How long it takes for the camera to reach this room"));
                #endif
                EditorGUI.PropertyField(new Rect(
                                            rect.x + 260,
                                            rect.y + 45,
                                            rect.width - 260,
                                            EditorGUIUtility.singleLineHeight),
                                        element.FindPropertyRelative("TransitionDuration"), GUIContent.none);

                #if UNITY_5_6_OR_NEWER
                EditorGUI.PrefixLabel(new Rect(rect.x, rect.y + 70, 65, 10), new GUIContent("Scale To Fit", "If checked, the camera will resize to fit the room"), EditorStyles.boldLabel);
                #else
                EditorGUI.PrefixLabel(new Rect(rect.x, rect.y + 70, 65, 10), new GUIContent("Scale To Fit", "If checked, the camera will resize to fit the room"));
                #endif
                EditorGUI.PropertyField(new Rect(
                                            rect.x + 80,
                                            rect.y + 70,
                                            20,
                                            EditorGUIUtility.singleLineHeight),
                                        element.FindPropertyRelative("ScaleCameraToFit"), GUIContent.none);

                GUI.enabled = !element.FindPropertyRelative("ScaleCameraToFit").boolValue;
                #if UNITY_5_6_OR_NEWER
                EditorGUI.PrefixLabel(new Rect(rect.x + 120, rect.y + 70, 65, 10), new GUIContent("Zoom", "If checked, the camera will zoom when entering the room"), EditorStyles.boldLabel);
                #else
                EditorGUI.PrefixLabel(new Rect(rect.x + 120, rect.y + 70, 65, 10), new GUIContent("Zoom", "If checked, the camera will zoom when entering the room"));
                #endif
                EditorGUI.PropertyField(new Rect(
                                            rect.x + 160,
                                            rect.y + 70,
                                            20,
                                            EditorGUIUtility.singleLineHeight),
                                        element.FindPropertyRelative("Zoom"), GUIContent.none);
                GUI.enabled = true;

                GUI.enabled = !element.FindPropertyRelative("ScaleCameraToFit").boolValue&& element.FindPropertyRelative("Zoom").boolValue;
                #if UNITY_5_6_OR_NEWER
                EditorGUI.PrefixLabel(new Rect(rect.x + 200, rect.y + 70, 65, 10), new GUIContent("Scale", "The zoom scale"), EditorStyles.boldLabel);
                #else
                EditorGUI.PrefixLabel(new Rect(rect.x + 200, rect.y + 70, 65, 10), new GUIContent("Scale", "The zoom scale"));
                #endif
                EditorGUI.PropertyField(new Rect(
                                            rect.x + 260,
                                            rect.y + 70,
                                            rect.width - 260,
                                            EditorGUIUtility.singleLineHeight),
                                        element.FindPropertyRelative("ZoomScale"), GUIContent.none);
                GUI.enabled = true;
            };

            _roomsList.elementHeight = 130;
            _roomsList.draggable     = true;
        }
Exemplo n.º 30
0
        /// <summary>
        /// Converts a MMFeedbacks and all its contents into the new and improved MMF_Player
        /// To convert from MMFeedbacks to MMF_Player you have a few options :
        /// - on a MMFeedbacks Settings panel, press the Generate MMF_Player button, this will create a new MMF_Player component on the same object, and copy feedbacks to it, ready to use.
        ///     The old MMFeedbacks won't be touched.
        /// - press the Convert feedback, and this will try to replace the current MMFeedbacks with a new MMF_Player with the same settings.
        /// - if you're inside a prefab instance, regular replace won't work, and you'll want to add, at the prefab level, an empty MMF_Player that will be the recipient of the conversion
        ///
        /// </summary>
        public virtual void ConvertToMMF_Player(bool generateOnly)
        {
            GameObject targetObject = _targetMMFeedbacks.gameObject;
            MMF_Player oldMMFPlayer = targetObject.GetComponent <MMF_Player>();

            // we remove any MMF_Player that may already be on that object
            if ((oldMMFPlayer != null) && (oldMMFPlayer.FeedbacksList.Count > 0))
            {
                DestroyImmediate(oldMMFPlayer);
            }

            // if we don't have an old player to work with and are inside a prefab, we give up to not break stuff
            if (!generateOnly && (oldMMFPlayer == null))
            {
                // conversion can't happen on a prefab instance unfortunately
                if (PrefabUtility.IsPartOfPrefabAsset(targetObject) ||
                    PrefabUtility.IsPartOfPrefabInstance(targetObject) ||
                    PrefabUtility.IsPartOfNonAssetPrefabInstance(targetObject))
                {
                    Debug.LogWarning("Unfortunately, you can't use conversion on a prefab instance.");
                    return;
                }
            }

            _canDisplayInspector = false;
            serializedObject.Update();
            Undo.RegisterCompleteObjectUndo(target, "Convert to MMF_Player");
            Debug.Log("Starting conversion to MMF_Player --------");

            if (generateOnly)
            {
                // we create a new player
                if (oldMMFPlayer == null)
                {
                    MMF_Player newPlayer = targetObject.AddComponent <MMF_Player>();
                    CopyFromMMFeedbacksToMMF_Player(newPlayer);
                }
                else
                {
                    CopyFromMMFeedbacksToMMF_Player(oldMMFPlayer);
                }
                serializedObject.ApplyModifiedProperties();
                return;
            }

            GameObject temporaryHost = null;

            // we create a new player
            if (oldMMFPlayer == null)
            {
                temporaryHost = new GameObject("TemporaryHost");
                MMF_Player newPlayer = temporaryHost.AddComponent <MMF_Player>();
                CopyFromMMFeedbacksToMMF_Player(newPlayer);

                MonoScript         yourReplacementScript = MonoScript.FromMonoBehaviour(newPlayer);
                SerializedProperty scriptProperty        = serializedObject.FindProperty("m_Script");
                serializedObject.Update();
                scriptProperty.objectReferenceValue = yourReplacementScript;
                serializedObject.ApplyModifiedProperties();

                // we copy back from our temp object
                MMF_Player finalPlayer = targetObject.GetComponent <MMF_Player>();
                finalPlayer.InitializationMode         = newPlayer.InitializationMode;
                finalPlayer.SafeMode                   = newPlayer.SafeMode;
                finalPlayer.Direction                  = newPlayer.Direction;
                finalPlayer.AutoChangeDirectionOnEnd   = newPlayer.AutoChangeDirectionOnEnd;
                finalPlayer.AutoPlayOnStart            = newPlayer.AutoPlayOnStart;
                finalPlayer.AutoPlayOnEnable           = newPlayer.AutoPlayOnEnable;
                finalPlayer.DurationMultiplier         = newPlayer.DurationMultiplier;
                finalPlayer.DisplayFullDurationDetails = newPlayer.DisplayFullDurationDetails;
                finalPlayer.CooldownDuration           = newPlayer.CooldownDuration;
                finalPlayer.InitialDelay               = newPlayer.InitialDelay;
                finalPlayer.CanPlayWhileAlreadyPlaying = newPlayer.CanPlayWhileAlreadyPlaying;
                finalPlayer.FeedbacksIntensity         = newPlayer.FeedbacksIntensity;
                finalPlayer.Events        = newPlayer.Events;
                finalPlayer.FeedbacksList = newPlayer.FeedbacksList;
                if (finalPlayer.FeedbacksList != null && finalPlayer.FeedbacksList.Count > 0)
                {
                    foreach (MMF_Feedback feedback in finalPlayer.FeedbacksList)
                    {
                        feedback.Owner    = finalPlayer;
                        feedback.UniqueID = Guid.NewGuid().GetHashCode();
                    }
                }
            }
            else
            {
                CopyFromMMFeedbacksToMMF_Player(oldMMFPlayer);
                PrefabUtility.RecordPrefabInstancePropertyModifications(oldMMFPlayer);
                serializedObject.Update();
                serializedObject.ApplyModifiedProperties();
                DestroyImmediate(_targetMMFeedbacks);
            }

            // we remove all remaining feedbacks
            Component[] feedbackArray = targetObject.GetComponents(typeof(MMFeedback));
            foreach (Component comp in feedbackArray)
            {
                DestroyImmediate(comp);
            }

            if (temporaryHost != null)
            {
                DestroyImmediate(temporaryHost);
            }

            Debug.Log("Conversion complete --------");
        }