public override void OnGUI(Rect position, MaterialProperty prop, GUIContent label, MaterialEditor editor)
    {
        position.height = 20;

        EditorGUI.LabelField(position, label);

        Rect  curvePosition = position;
        float newWidth      = curvePosition.width * 0.6f;

        curvePosition.x    += curvePosition.width - newWidth;
        curvePosition.width = newWidth;

        if (curve == null)
        {
            LoadCurveData(prop, editor.target as Material);
        }

        EditorGUI.BeginChangeCheck();

        curve = EditorGUI.CurveField(curvePosition, curve, Color.green, curveRange);

        if (EditorGUI.EndChangeCheck())
        {
            DisplayCurveChange(prop);

            needToBake = true;
        }

        EditorGUI.indentLevel = 1;

        EditorGUI.BeginChangeCheck();

        position.y += 22;

        textureResolution = EditorGUI.DelayedIntField(position, "Resolution", textureResolution);

        if (EditorGUI.EndChangeCheck())
        {
            DisplayCurveChange(prop);

            needToBake = true;
        }

        position.y += 22;

        EditorGUI.LabelField(position, "Range");

        newWidth            = position.width * 0.4f;
        curvePosition.x    += curvePosition.width - newWidth;
        curvePosition.width = newWidth;
        curvePosition.y    += 44;

        EditorGUI.BeginChangeCheck();

        curveRange = EditorGUI.RectField(curvePosition, curveRange);

        if (EditorGUI.EndChangeCheck())
        {
            SaveRange(prop, editor.target as Material);
        }

        EditorGUI.indentLevel = 0;

        Assembly  assembly = Assembly.GetAssembly(typeof(Editor));
        Type      type     = assembly.GetType("UnityEditor.CurveEditorWindow");
        FieldInfo field    = type.GetField("s_SharedCurveEditor", BindingFlags.NonPublic | BindingFlags.Static);

        if (field.GetValue(null) == null)
        {
            if (needToBake)
            {
                needToBake = false;

                BakeCurveTexture(prop, editor.target as Material);
            }
        }
    }
Esempio n. 2
0
        private void InitReorderedList()
        {
            if (prefEntryHolder == null)
            {
                var tmp = Resources.FindObjectsOfTypeAll <PreferenceEntryHolder>();
                if (tmp.Length > 0)
                {
                    prefEntryHolder = tmp[0];
                }
                else
                {
                    prefEntryHolder = ScriptableObject.CreateInstance <PreferenceEntryHolder>();
                }
            }

            if (serializedObject == null)
            {
                serializedObject = new SerializedObject(prefEntryHolder);
            }

            userDefList  = new ReorderableList(serializedObject, serializedObject.FindProperty("userDefList"), false, true, true, true);
            unityDefList = new ReorderableList(serializedObject, serializedObject.FindProperty("unityDefList"), false, true, false, false);

            relSpliterPos = EditorPrefs.GetFloat("BGTools.PlayerPrefsEditor.RelativeSpliterPosition", 100 / position.width);

            userDefList.drawHeaderCallback = (Rect rect) =>
            {
                EditorGUI.LabelField(rect, "User defined");
            };
            userDefList.drawElementBackgroundCallback = OnDrawElementBackgroundCallback;
            userDefList.drawElementCallback           = (Rect rect, int index, bool isActive, bool isFocused) =>
            {
                var element                   = userDefList.serializedProperty.GetArrayElementAtIndex(index);
                SerializedProperty key        = element.FindPropertyRelative("m_key");
                SerializedProperty type       = element.FindPropertyRelative("m_typeSelection");
                SerializedProperty strValue   = element.FindPropertyRelative("m_strValue");
                SerializedProperty intValue   = element.FindPropertyRelative("m_intValue");
                SerializedProperty floatValue = element.FindPropertyRelative("m_floatValue");
                float spliterPos              = relSpliterPos * rect.width;

                rect.y += 2;

                EditorGUI.BeginChangeCheck();
                EditorGUI.LabelField(new Rect(rect.x, rect.y, spliterPos - 1, EditorGUIUtility.singleLineHeight), new GUIContent(key.stringValue, key.stringValue));
                GUI.enabled = false;
                EditorGUI.PropertyField(new Rect(rect.x + spliterPos + 1, rect.y, 60, EditorGUIUtility.singleLineHeight), type, GUIContent.none);
                GUI.enabled = !showLoadingIndicatorOverlay;
                switch ((PreferenceEntry.PrefTypes)type.enumValueIndex)
                {
                case PreferenceEntry.PrefTypes.Float:
                    EditorGUI.DelayedFloatField(new Rect(rect.x + spliterPos + 62, rect.y, rect.width - spliterPos - 60, EditorGUIUtility.singleLineHeight), floatValue, GUIContent.none);
                    break;

                case PreferenceEntry.PrefTypes.Int:
                    EditorGUI.DelayedIntField(new Rect(rect.x + spliterPos + 62, rect.y, rect.width - spliterPos - 60, EditorGUIUtility.singleLineHeight), intValue, GUIContent.none);
                    break;

                case PreferenceEntry.PrefTypes.String:
                    EditorGUI.DelayedTextField(new Rect(rect.x + spliterPos + 62, rect.y, rect.width - spliterPos - 60, EditorGUIUtility.singleLineHeight), strValue, GUIContent.none);
                    break;
                }
                if (EditorGUI.EndChangeCheck())
                {
                    entryAccessor.IgnoreNextChange();

                    switch ((PreferenceEntry.PrefTypes)type.enumValueIndex)
                    {
                    case PreferenceEntry.PrefTypes.Float:
                        PlayerPrefs.SetFloat(key.stringValue, floatValue.floatValue);
                        break;

                    case PreferenceEntry.PrefTypes.Int:
                        PlayerPrefs.SetInt(key.stringValue, intValue.intValue);
                        break;

                    case PreferenceEntry.PrefTypes.String:
                        PlayerPrefs.SetString(key.stringValue, strValue.stringValue);
                        break;
                    }

                    PlayerPrefs.Save();
                }
            };
            userDefList.onRemoveCallback = (ReorderableList l) =>
            {
                userDefList.ReleaseKeyboardFocus();
                unityDefList.ReleaseKeyboardFocus();

                if (EditorUtility.DisplayDialog("Warning!", "Are you sure you want to delete this entry from PlayerPrefs? ", "Yes", "No"))
                {
                    entryAccessor.IgnoreNextChange();

                    PlayerPrefs.DeleteKey(l.serializedProperty.GetArrayElementAtIndex(l.index).FindPropertyRelative("m_key").stringValue);
                    PlayerPrefs.Save();

                    ReorderableList.defaultBehaviours.DoRemoveButton(l);
                    PrepareData();
                    GUIUtility.ExitGUI();
                }
            };
            userDefList.onAddDropdownCallback = (Rect buttonRect, ReorderableList l) =>
            {
                var menu = new GenericMenu();
                foreach (PreferenceEntry.PrefTypes type in Enum.GetValues(typeof(PreferenceEntry.PrefTypes)))
                {
                    menu.AddItem(new GUIContent(type.ToString()), false, () =>
                    {
                        TextFieldDialog.OpenDialog("Create new property", "Key for the new property:", prefKeyValidatorList, (key) => {
                            entryAccessor.IgnoreNextChange();

                            switch (type)
                            {
                            case PreferenceEntry.PrefTypes.Float:
                                PlayerPrefs.SetFloat(key, 0.0f);

                                break;

                            case PreferenceEntry.PrefTypes.Int:
                                PlayerPrefs.SetInt(key, 0);

                                break;

                            case PreferenceEntry.PrefTypes.String:
                                PlayerPrefs.SetString(key, string.Empty);

                                break;
                            }
                            PlayerPrefs.Save();

                            PrepareData();

                            Focus();
                        }, this);
                    });
                }
                menu.ShowAsContext();
            };

            unityDefList.drawElementBackgroundCallback = OnDrawElementBackgroundCallback;
            unityDefList.drawElementCallback           = (Rect rect, int index, bool isActive, bool isFocused) =>
            {
                var element                   = unityDefList.serializedProperty.GetArrayElementAtIndex(index);
                SerializedProperty key        = element.FindPropertyRelative("m_key");
                SerializedProperty type       = element.FindPropertyRelative("m_typeSelection");
                SerializedProperty strValue   = element.FindPropertyRelative("m_strValue");
                SerializedProperty intValue   = element.FindPropertyRelative("m_intValue");
                SerializedProperty floatValue = element.FindPropertyRelative("m_floatValue");
                float spliterPos              = relSpliterPos * rect.width;

                rect.y += 2;

                GUI.enabled = false;
                EditorGUI.LabelField(new Rect(rect.x, rect.y, spliterPos - 1, EditorGUIUtility.singleLineHeight), new GUIContent(key.stringValue, key.stringValue));
                EditorGUI.PropertyField(new Rect(rect.x + spliterPos + 1, rect.y, 60, EditorGUIUtility.singleLineHeight), type, GUIContent.none);

                switch ((PreferenceEntry.PrefTypes)type.enumValueIndex)
                {
                case PreferenceEntry.PrefTypes.Float:
                    EditorGUI.DelayedFloatField(new Rect(rect.x + spliterPos + 62, rect.y, rect.width - spliterPos - 60, EditorGUIUtility.singleLineHeight), floatValue, GUIContent.none);
                    break;

                case PreferenceEntry.PrefTypes.Int:
                    EditorGUI.DelayedIntField(new Rect(rect.x + spliterPos + 62, rect.y, rect.width - spliterPos - 60, EditorGUIUtility.singleLineHeight), intValue, GUIContent.none);
                    break;

                case PreferenceEntry.PrefTypes.String:
                    EditorGUI.DelayedTextField(new Rect(rect.x + spliterPos + 62, rect.y, rect.width - spliterPos - 60, EditorGUIUtility.singleLineHeight), strValue, GUIContent.none);
                    break;
                }
                GUI.enabled = !showLoadingIndicatorOverlay;
            };
            unityDefList.drawHeaderCallback = (Rect rect) =>
            {
                EditorGUI.LabelField(rect, "Unity defined");
            };
        }
Esempio n. 3
0
        public static object ValueField(Rect rect, object value, Type type)
        {
            object     newValue     = value;
            GUIContent labelContent = GUIContent.none;
            var        typeCode     = SerializableValue.TypeToSerializableTypeCode(type);

            switch (typeCode)
            {
            case SerializableTypeCode.String:
            {
                string str = value as string;
                str      = str ?? "";
                newValue = EditorGUI.DelayedTextField(rect, str);
            }
            break;

            case SerializableTypeCode.Int32:
            {
                int n = (int)value;
                newValue = EditorGUI.DelayedIntField(rect, n);
            }
            break;

            case SerializableTypeCode.Single:
            {
                float f = (float)value;
                newValue = EditorGUI.DelayedFloatField(rect, f);
            }
            break;

            case SerializableTypeCode.Boolean:
            {
                bool b;
                b        = (bool)value;
                newValue = EditorGUI.Toggle(rect, b);
            }
            break;

            case SerializableTypeCode.UnityObject:
            {
                UnityEngine.Object obj = value as UnityEngine.Object;
                newValue = EditorGUI.ObjectField(rect, obj, type, true);
            }
            break;

            case SerializableTypeCode.Vector2:
            {
                Vector2 v = (Vector2)value;
                newValue = EditorGUI.Vector2Field(rect, labelContent, v);
            }
            break;

            case SerializableTypeCode.Vector3:
            {
                Vector3 v = (Vector3)value;
                newValue = EditorGUI.Vector3Field(rect, labelContent, v);
            }
            break;

            case SerializableTypeCode.Vector4:
            {
                Vector4 v = (Vector4)value;
                newValue = EditorGUI.Vector4Field(rect, labelContent, v);
            }
            break;

            case SerializableTypeCode.Color:
            {
                Color v = (Color)value;
                newValue = EditorGUI.ColorField(rect, labelContent, v);
            }
            break;

            case SerializableTypeCode.Rect:
            {
                Rect v = (Rect)value;
                newValue = EditorGUI.RectField(rect, labelContent, v);
            }
            break;

            case SerializableTypeCode.Bounds:
            {
                Bounds v = (Bounds)value;
                newValue = EditorGUI.BoundsField(rect, labelContent, v);
            }
            break;

            case SerializableTypeCode.AnimationCurve:
            {
                AnimationCurve v = (AnimationCurve)value;
                newValue = EditorGUI.CurveField(rect, labelContent, v);
            }
            break;
            }
            return(newValue);
        }
        Vector2 DrawWeaponConfigurator(float startX, float startY, Weapon weapon)
        {
            //float cachedX=startX;
            //float cachedY=startY;

            TDSEditorUtility.DrawSprite(new Rect(startX, startY, 60, 60), weapon.icon);
            startX += 65;

            float offsetY = TDSEditor.IsPrefab(weapon.gameObject) ? 5 : 0;

            cont = new GUIContent("Name:", "The weapon name to be displayed in game");
            EditorGUI.LabelField(new Rect(startX, startY += offsetY, width, height), cont);
            weapon.weaponName = EditorGUI.DelayedTextField(new Rect(startX + spaceX - 65, startY, width - 5, height), weapon.weaponName);

            cont = new GUIContent("Icon:", "The weapon icon to be displayed in game, must be a sprite");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);
            weapon.icon = (Sprite)EditorGUI.ObjectField(new Rect(startX + spaceX - 65, startY, width - 5, height), weapon.icon, typeof(Sprite), false);

            cont = new GUIContent("Prefab:", "The prefab object of the weapon\nClick this to highlight it in the ProjectTab");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);
            EditorGUI.ObjectField(new Rect(startX + spaceX - 65, startY, width - 5, height), weapon.gameObject, typeof(GameObject), false);

            startX -= 65;
            startY += spaceY;           //cachedY=startY;


            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), "Weapon Stats", headerStyle);

            cont = new GUIContent("Shoot Object:", "The prefab of the bullet/object fired by the weapon\nMust be a prefab with ShootObject component attached on it");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);
            weapon.shootObject = (GameObject)EditorGUI.ObjectField(new Rect(startX + spaceX, startY, width, height), weapon.shootObject, typeof(GameObject), false);

            cont = new GUIContent("ShootPoint:", "The transform which indicate the position where the shootObject will be fired from (Optional)\nEach shootPoint assigned will fire a shootObject instance in each attack\nIf left empty, the weapon transform itself will be use as the shootPoint\nThe orientation of the shootPoint matter as they dictate the orientation of the firing direction.\n");
            shootPointFoldout = EditorGUI.Foldout(new Rect(startX, startY += spaceY, spaceX, height), shootPointFoldout, cont);
            int shootPointCount = weapon.shootPointList.Count;

            shootPointCount = EditorGUI.DelayedIntField(new Rect(startX + spaceX, startY, 40, height), shootPointCount);

            if (shootPointCount != weapon.shootPointList.Count)
            {
                while (weapon.shootPointList.Count < shootPointCount)
                {
                    weapon.shootPointList.Add(null);
                }
                while (weapon.shootPointList.Count > shootPointCount)
                {
                    weapon.shootPointList.RemoveAt(weapon.shootPointList.Count - 1);
                }
            }

            if (shootPointFoldout)
            {
                for (int i = 0; i < weapon.shootPointList.Count; i++)
                {
                    int objID = GetObjectIDFromHList(weapon.shootPointList[i], objHList);
                    EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), "    - Element " + (i + 1));
                    objID = EditorGUI.Popup(new Rect(startX + spaceX, startY, width, height), objID, objHLabelList);
                    weapon.shootPointList[i] = (objHList[objID] == null) ? null : objHList[objID].transform;
                }
            }

            cont = new GUIContent("Shoot Point Delay:", "The delay in seconds between subsequent shot in each shoot point");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);
            if (weapon.shootPointList.Count > 1)
            {
                weapon.shootPointDelay = EditorGUI.DelayedFloatField(new Rect(startX + spaceX, startY, 40, height), weapon.shootPointDelay);
            }
            else
            {
                EditorGUI.LabelField(new Rect(startX + spaceX, startY, 40, height), "-");
            }


            startY += 5;

            cont = new GUIContent("Continous Fire:", "Check to enable continous firing on the weapon when holding down fire button");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);
            weapon.continousFire = EditorGUI.Toggle(new Rect(startX + spaceX, startY, 40, height), weapon.continousFire);

            startY += 5;

            cont = new GUIContent("Range:", "The effective range of the weapon.");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);
            weapon.range = EditorGUI.DelayedFloatField(new Rect(startX + spaceX, startY, 40, height), weapon.range);

            cont = new GUIContent("Cooldown:", "The cooldown in seconds between subsequent shot");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);
            weapon.cooldown = EditorGUI.DelayedFloatField(new Rect(startX + spaceX, startY, 40, height), weapon.cooldown);

            startY += 5;

            cont = new GUIContent("UseEnergyAsAmmo:", "Check to use energy as ammunition");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);
            weapon.useEnergyAsAmmo = EditorGUI.Toggle(new Rect(startX + spaceX, startY, 40, height), weapon.useEnergyAsAmmo);

            cont = new GUIContent(" - Cost Per Shot:", "The energy cost per shot");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);
            if (!weapon.useEnergyAsAmmo)
            {
                EditorGUI.LabelField(new Rect(startX + spaceX, startY, 40, height), "-");
            }
            else
            {
                weapon.energyCost = EditorGUI.DelayedFloatField(new Rect(startX + spaceX, startY, 40, height), weapon.energyCost);
            }

            startY += 5;

            cont = new GUIContent("Clip Size:", "How many times the weapon can be fired before it needs a reload. Set to -1 if the weapon can be fired indefinitely without reloading");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);
            if (weapon.useEnergyAsAmmo)
            {
                EditorGUI.LabelField(new Rect(startX + spaceX, startY, 40, height), "-");
            }
            else
            {
                weapon.clipSize = EditorGUI.DelayedIntField(new Rect(startX + spaceX, startY, 40, height), weapon.clipSize);
            }

            cont = new GUIContent("Ammo Cap:", "How many ammo of the weapon the player can keep. Set to -1 if the weapon has unlimited ammo cap");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);
            if (weapon.useEnergyAsAmmo)
            {
                EditorGUI.LabelField(new Rect(startX + spaceX, startY, 40, height), "-");
            }
            else
            {
                weapon.ammoCap = EditorGUI.DelayedIntField(new Rect(startX + spaceX, startY, 40, height), weapon.ammoCap);
            }

            cont = new GUIContent("Reload Duration:", "The duration in seconds to reload the weapon");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);
            if (weapon.useEnergyAsAmmo)
            {
                EditorGUI.LabelField(new Rect(startX + spaceX, startY, 40, height), "-");
            }
            else
            {
                weapon.reloadDuration = EditorGUI.DelayedFloatField(new Rect(startX + spaceX, startY, 40, height), weapon.reloadDuration);
            }

            startY += 5;

            cont = new GUIContent("Recoil:", "The recoil magnitude of the weapon. The higher the value, the less accurate the weapon become when fired continously");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);
            weapon.recoilMagnitude = EditorGUI.DelayedFloatField(new Rect(startX + spaceX, startY, 40, height), weapon.recoilMagnitude);

            cont = new GUIContent("Recoil Cam Shake:", "The camera shake magnitude whenever the weapon is fired");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);
            weapon.recoilCamShake = EditorGUI.DelayedFloatField(new Rect(startX + spaceX, startY, 40, height), weapon.recoilCamShake);

            startY += 5;

            cont = new GUIContent("Spread:", "The number of shoot object split from each shoot point. This is to create a shotgun effect");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);
            weapon.spread = EditorGUI.DelayedIntField(new Rect(startX + spaceX, startY, 40, height), weapon.spread);
            weapon.spread = Mathf.Max(1, weapon.spread);

            cont = new GUIContent("Spread Angle:", "The angle (in degree) between each spread");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);
            if (weapon.spread > 1)
            {
                weapon.spreadAngle = EditorGUI.DelayedFloatField(new Rect(startX + spaceX, startY, 40, height), weapon.spreadAngle);
            }
            else
            {
                EditorGUI.LabelField(new Rect(startX + spaceX, startY, 40, height), "-");
            }

            startY += 10;

            Vector2 v2 = DrawAttackStats1(startX, startY + spaceY, weapon.aStats);

            startY = v2.y + 20;

            startY += 30;


            //int abilityIdx=weapon.ability==null ? 0 : TDSEditor.GetEffectIndex(weapon.ability.ID);
            //if(abilityIdx==0) weapon.ability=null;
            int abilityIdx = weapon.abilityID >= 0 ? TDSEditor.GetAbilityIndex(weapon.abilityID) : 0;

            TDSEditorUtility.DrawSprite(new Rect(startX + spaceX + width - 40, startY + spaceY - 45, 40, 40), abilityIdx > 0 ? abilityDB.abilityList[abilityIdx - 1].icon : null);
            if (GUI.Button(new Rect(startX + spaceX, startY - 2, 40, height - 2), "Edit "))
            {
                AbilityEditorWindow.Init();
            }

            cont = new GUIContent("AltAttack(Ability):", "Ability that is being used as the weapon alternate fire mode (optional)");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY - 5, width, height), cont, headerStyle);

            abilityIdx = EditorGUI.Popup(new Rect(startX + spaceX, startY, width, height), abilityIdx, abilityLabel);
            if (abilityIdx > 0)
            {
                weapon.abilityID = abilityDB.abilityList[abilityIdx - 1].ID;
            }
            else
            {
                weapon.abilityID = -1;
            }

            //if(abilityIdx>0) weapon.ability=abilityDB.abilityList[abilityIdx-1];
            //else weapon.ability=null;


            startY += 15;


            cont = new GUIContent("Shoot SFX:", "Audio clip to play when the weapon fires (optional)");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);
            weapon.shootSFX = (AudioClip)EditorGUI.ObjectField(new Rect(startX + spaceX, startY, width, height), weapon.shootSFX, typeof(AudioClip), false);

            cont = new GUIContent("Reload SFX:", "Audio clip to play when the weapon reloads (optional)");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);
            weapon.reloadSFX = (AudioClip)EditorGUI.ObjectField(new Rect(startX + spaceX, startY, width, height), weapon.reloadSFX, typeof(AudioClip), false);


            startY += 15;

            GUIStyle style = new GUIStyle("TextArea");

            style.wordWrap = true;
            cont           = new GUIContent("Weapon description (to be used in runtime): ", "");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, 400, 20), cont);
            weapon.desp = EditorGUI.DelayedTextField(new Rect(startX, startY + spaceY - 3, 270, 150), weapon.desp, style);


            return(new Vector2(startX, startY + 200));
        }
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            SerializedProperty prop_SpriteName         = property.FindPropertyRelative("m_Name");
            SerializedProperty prop_SpriteNameHashCode = property.FindPropertyRelative("m_HashCode");
            SerializedProperty prop_SpriteUnicode      = property.FindPropertyRelative("m_Unicode");
            SerializedProperty prop_SpriteGlyphIndex   = property.FindPropertyRelative("m_GlyphIndex");
            SerializedProperty prop_SpriteScale        = property.FindPropertyRelative("m_Scale");


            GUIStyle style = new GUIStyle(EditorStyles.label);

            style.richText = true;

            EditorGUIUtility.labelWidth = 40f;
            EditorGUIUtility.fieldWidth = 50;

            Rect rect = new Rect(position.x + 60, position.y, position.width, 49);

            // Display non-editable fields
            if (GUI.enabled == false)
            {
                // Sprite Character Index
                int spriteCharacterIndex;
                int.TryParse(property.displayName.Split(' ')[1], out spriteCharacterIndex);
                EditorGUI.LabelField(new Rect(rect.x, rect.y, 75f, 18), new GUIContent("Index: <color=#FFFF80>" + spriteCharacterIndex + "</color>"), style);

                EditorGUI.LabelField(new Rect(rect.x + 75f, rect.y, 120f, 18), new GUIContent("Unicode: <color=#FFFF80>0x" + prop_SpriteUnicode.intValue.ToString("X") + "</color>"), style);
                EditorGUI.LabelField(new Rect(rect.x + 195f, rect.y, rect.width - 255, 18), new GUIContent("Name: <color=#FFFF80>" + prop_SpriteName.stringValue + "</color>"), style);

                EditorGUI.LabelField(new Rect(rect.x, rect.y + 18, 120, 18), new GUIContent("Glyph ID: <color=#FFFF80>" + prop_SpriteGlyphIndex.intValue + "</color>"), style);

                // Draw Sprite Glyph (if exists)
                DrawSpriteGlyph(position, property);

                EditorGUI.LabelField(new Rect(rect.x, rect.y + 36, 80, 18), new GUIContent("Scale: <color=#FFFF80>" + prop_SpriteScale.floatValue + "</color>"), style);
            }
            else // Display editable fields
            {
                // Get a reference to the underlying Sprite Asset
                TMP_SpriteAsset spriteAsset = property.serializedObject.targetObject as TMP_SpriteAsset;

                // Sprite Character Index
                int spriteCharacterIndex;
                int.TryParse(property.displayName.Split(' ')[1], out spriteCharacterIndex);

                EditorGUI.LabelField(new Rect(rect.x, rect.y, 75f, 18), new GUIContent("Index: <color=#FFFF80>" + spriteCharacterIndex + "</color>"), style);

                EditorGUIUtility.labelWidth = 55f;
                GUI.SetNextControlName("Unicode Input");
                EditorGUI.BeginChangeCheck();
                string unicode = EditorGUI.DelayedTextField(new Rect(rect.x + 75f, rect.y, 120, 18), "Unicode:", prop_SpriteUnicode.intValue.ToString("X"));

                if (GUI.GetNameOfFocusedControl() == "Unicode Input")
                {
                    //Filter out unwanted characters.
                    char chr = Event.current.character;
                    if ((chr < '0' || chr > '9') && (chr < 'a' || chr > 'f') && (chr < 'A' || chr > 'F'))
                    {
                        Event.current.character = '\0';
                    }
                }

                if (EditorGUI.EndChangeCheck())
                {
                    // Update Unicode value
                    prop_SpriteUnicode.intValue = TMP_TextUtilities.StringHexToInt(unicode);
                    spriteAsset.m_IsSpriteAssetLookupTablesDirty = true;
                }

                EditorGUIUtility.labelWidth = 41f;
                EditorGUI.BeginChangeCheck();
                EditorGUI.DelayedTextField(new Rect(rect.x + 195f, rect.y, rect.width - 255, 18), prop_SpriteName, new GUIContent("Name:"));
                if (EditorGUI.EndChangeCheck())
                {
                    // Recompute hashCode for new name
                    prop_SpriteNameHashCode.intValue             = TMP_TextUtilities.GetSimpleHashCode(prop_SpriteName.stringValue);
                    spriteAsset.m_IsSpriteAssetLookupTablesDirty = true;
                }

                EditorGUIUtility.labelWidth = 59f;
                EditorGUI.BeginChangeCheck();
                EditorGUI.DelayedIntField(new Rect(rect.x, rect.y + 18, 100, 18), prop_SpriteGlyphIndex, new GUIContent("Glyph ID:"));
                if (EditorGUI.EndChangeCheck())
                {
                    spriteAsset.m_IsSpriteAssetLookupTablesDirty = true;
                }

                // Draw Sprite Glyph (if exists)
                DrawSpriteGlyph(position, property);

                int glyphIndex = prop_SpriteGlyphIndex.intValue;

                // Reset glyph selection if new character has been selected.
                if (GUI.enabled && m_GlyphSelectedForEditing != glyphIndex)
                {
                    m_GlyphSelectedForEditing = -1;
                }

                // Display button to edit the glyph data.
                if (GUI.Button(new Rect(rect.x + 120, rect.y + 18, 75, 18), new GUIContent("Edit Glyph")))
                {
                    if (m_GlyphSelectedForEditing == -1)
                    {
                        m_GlyphSelectedForEditing = glyphIndex;
                    }
                    else
                    {
                        m_GlyphSelectedForEditing = -1;
                    }

                    // Button clicks should not result in potential change.
                    GUI.changed = false;
                }

                // Show the glyph property drawer if selected
                if (glyphIndex == m_GlyphSelectedForEditing && GUI.enabled)
                {
                    if (spriteAsset != null)
                    {
                        // Lookup glyph and draw glyph (if available)
                        int elementIndex = spriteAsset.spriteGlyphTable.FindIndex(item => item.index == glyphIndex);

                        if (elementIndex != -1)
                        {
                            // Get a reference to the Sprite Glyph Table
                            SerializedProperty prop_SpriteGlyphTable = property.serializedObject.FindProperty("m_SpriteGlyphTable");

                            SerializedProperty prop_SpriteGlyph  = prop_SpriteGlyphTable.GetArrayElementAtIndex(elementIndex);
                            SerializedProperty prop_GlyphMetrics = prop_SpriteGlyph.FindPropertyRelative("m_Metrics");
                            SerializedProperty prop_GlyphRect    = prop_SpriteGlyph.FindPropertyRelative("m_GlyphRect");

                            Rect newRect = EditorGUILayout.GetControlRect(false, 115);
                            EditorGUI.DrawRect(new Rect(newRect.x + 62, newRect.y - 20, newRect.width - 62, newRect.height - 5), new Color(0.1f, 0.1f, 0.1f, 0.45f));
                            EditorGUI.DrawRect(new Rect(newRect.x + 63, newRect.y - 19, newRect.width - 64, newRect.height - 7), new Color(0.3f, 0.3f, 0.3f, 0.8f));

                            // Display GlyphRect
                            newRect.x     += 65;
                            newRect.y     -= 18;
                            newRect.width += 5;
                            EditorGUI.PropertyField(newRect, prop_GlyphRect);

                            // Display GlyphMetrics
                            newRect.y += 45;
                            EditorGUI.PropertyField(newRect, prop_GlyphMetrics);

                            rect.y += 120;
                        }
                    }
                }

                EditorGUIUtility.labelWidth = 39f;
                EditorGUI.PropertyField(new Rect(rect.x, rect.y + 36, 80, 18), prop_SpriteScale, new GUIContent("Scale:"));
            }
        }
Esempio n. 6
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            base.OnGUI(position, property, label);

            string keyTypeName   = property.FindPropertyRelative(KEY_TYPENAME_FIELD_NAME).stringValue;
            string valueTypeName = property.FindPropertyRelative(VALUE_TYPENAME_FIELD_NAME).stringValue;

            label.text = ObjectNames.NicifyVariableName(this.fieldInfo.Name) + " <" + keyTypeName + ", " + valueTypeName + ">";

            EditorGUI.BeginProperty(position, label, property);

            property.isExpanded = EditorGUI.Foldout(GetRect(ref position), property.isExpanded, label, true);

            if (property.isExpanded)
            {
                BeginPadding(ref position, new Vector4(0, 5, 0, 0));

                Indent(ref position);

                SerializedProperty entries       = property.FindPropertyRelative(ENTRIES_FIELD_NAME);
                SerializedProperty keyCollisions = property.FindPropertyRelative(KEY_COLLISIONS_FIELD_NAME);

                EditorGUIUtility.labelWidth = 50f;
                int size = EditorGUI.DelayedIntField(GetRect(ref position), new GUIContent("Size", "The size of the dictionary."), entries.arraySize);
                EditorGUIUtility.labelWidth = originalLabelWidth;
                GetRect(ref position, -1, 5f);

                size = Mathf.Max(size, 0);

                while (size > entries.arraySize)
                {
                    entries.arraySize++;
                }

                while (size < entries.arraySize && size >= 0)
                {
                    entries.arraySize--;
                }

                bool foundDuplicateKeys = false;
                for (int i = 0; i < entries.arraySize; i++)
                {
                    if (i == 0)
                    {
                        DrawLine(ref position, -1, 2);
                    }

                    SerializedProperty entry = entries.GetArrayElementAtIndex(i);
                    SerializedProperty key   = entry.FindPropertyRelative(ENTRY_KEY_FIELD_NAME);
                    SerializedProperty value = entry.FindPropertyRelative(ENTRY_VALUE_FIELD_NAME);

                    float seperatorWidth = 2f;
                    float buttonWidth    = 20f;
                    float keyWidth       = (position.width - buttonWidth - seperatorWidth - (horizontalSpacing * 2)) / 2f;
                    float keyHeight      = EditorGUI.GetPropertyHeight(key);
                    float valueWidth     = keyWidth;
                    float valueHeight    = EditorGUI.GetPropertyHeight(value);

                    if (keyHeight > valueHeight)
                    {
                        valueHeight = keyHeight;
                    }
                    else
                    {
                        keyHeight = valueHeight;
                    }

                    if (i < keyCollisions.arraySize && keyCollisions.GetArrayElementAtIndex(i).boolValue)
                    {
                        foundDuplicateKeys = true;
                        EditorGUI.DrawRect(new Rect(position.x, position.y, position.width, keyHeight), new Color(1, 0, 0, 0.15f));
                        GUI.backgroundColor = Color.red;
                    }
                    else
                    {
                        GUI.backgroundColor = originalBackgroundColor;
                    }

                    BeginHorizontal(ref position);

                    if (key.hasVisibleChildren)
                    {
                        EditorGUIUtility.labelWidth = indentSpacing;
                    }
                    EditorGUI.PropertyField(
                        GetRect(ref position, keyWidth, keyHeight),
                        key,
                        key.hasVisibleChildren ? new GUIContent(keyTypeName) : GUIContent.none,
                        true
                        );
                    if (key.hasVisibleChildren)
                    {
                        EditorGUIUtility.labelWidth = originalLabelWidth;
                    }

                    DrawLine(ref position, new Color(0, 0, 0, 0.5f), seperatorWidth, keyHeight);

                    if (value.hasVisibleChildren)
                    {
                        EditorGUIUtility.labelWidth = indentSpacing;
                    }
                    EditorGUI.PropertyField(
                        GetRect(ref position, valueWidth, valueHeight),
                        value,
                        value.hasVisibleChildren ? new GUIContent(valueTypeName) : GUIContent.none,
                        true
                        );
                    if (value.hasVisibleChildren)
                    {
                        EditorGUIUtility.labelWidth = originalLabelWidth;
                    }

                    GUI.backgroundColor = Color.red;
                    if (GUI.Button(GetRect(ref position, buttonWidth), "x"))
                    {
                        GUI.FocusControl(null);
                        entries.DeleteArrayElementAtIndex(i);
                    }
                    GUI.backgroundColor = originalBackgroundColor;

                    EndHorizontal(ref position);

                    DrawLine(ref position, -1, 1);
                }
                duplicateKeys = foundDuplicateKeys;

                GetRect(ref position, -1, 5f);
                if (GUI.Button(GetRect(ref position), "Add"))
                {
                    entries.arraySize++;
                }

                Indent(ref position, -1);

                EndPadding(ref position, new Vector4(0, 5, 0, 0));
                GUI.backgroundColor = new Color(1, 1, 1, 0);
                EditorGUI.HelpBox(new Rect(startPosition, new Vector2(position.width, height)), "", MessageType.None);
                GUI.backgroundColor = originalBackgroundColor;
            }

            if (duplicateKeys)
            {
                GetRect(ref position, -1, 1);

                // there are key collisions, so we render a warning box.
                EditorGUI.HelpBox(
                    GetRect(ref position, -1, EditorGUIUtility.singleLineHeight * 3),
                    "There are duplicate keys in the dictionary. Duplicates will be excluded.",
                    MessageType.Warning
                    );
            }

            EditorGUI.EndProperty();
        }
Esempio n. 7
0
        private float DrawLevelList(float startX, float startY, LevelProgressionStats stats)
        {
            startX += 60;

            EditorGUI.LabelField(new Rect(startX, startY, width, height), "Exp to level:", headerStyle);
            EditorGUI.LabelField(new Rect(startX + width - 15, startY, width, height), "Perk Gained:", headerStyle);

            startX += 5;

            //string textRS=stats.sumRecursively ? "Σ(" : "";
            //string textRE=stats.sumRecursively ? ")" : "";

            //EditorGUI.LabelField(new Rect(startX, startY+=spaceY, width+10, height), "exp = "+textRS+"("+stats.expTHM+"*lvl)+"+stats.expTHC+textRE, headerStyle);

            for (int i = 0; i < stats.expThresholdList.Count; i++)
            {
                float cachedX = startX;

                cont = new GUIContent(" - lvl " + (i + 1) + ":", "");
                EditorGUI.LabelField(new Rect(startX - 60, startY += spaceY, width, height), cont);

                if (i == 0)
                {
                    EditorGUI.LabelField(new Rect(startX, startY, widthS + spaceX - 85, height), "-");
                }
                else
                {
                    stats.expThresholdList[i] = EditorGUI.DelayedIntField(new Rect(startX, startY, widthS + spaceX - 85, height), stats.expThresholdList[i]);
                }

                int index = -1;
                for (int n = 0; n < stats.perkUnlockingAtLevelList.Count; n++)
                {
                    if (stats.perkUnlockingAtLevelList[n].level == i + 1)
                    {
                        index = n;      break;
                    }
                }

                if (index >= 0)
                {
                    float cachedX2 = startX += width - 20;

                    PerkUnlockingAtLevel item = stats.perkUnlockingAtLevelList[index];
                    for (int n = 0; n < item.perkIDList.Count; n++)
                    {
                        int perkIdx = TDSEditor.GetPerkIndex(item.perkIDList[n]);

                        if (perkIdx <= 0)
                        {
                            item.perkIDList.RemoveAt(n); n -= 1;
                        }
                        else
                        {
                            cont = new GUIContent(perkDB.perkList[perkIdx - 1].name, perkDB.perkList[perkIdx - 1].desp);
                            EditorGUI.LabelField(new Rect(startX, startY, width * .75f, height), cont);
                            if (GUI.Button(new Rect(startX - height - 5, startY, height, height), "-"))
                            {
                                item.perkIDList.RemoveAt(n); n -= 1;
                            }
                        }

                        startX += width * .75f;
                    }

                    startX = cachedX2;

                    if (item.perkIDList.Count == 0)
                    {
                        stats.perkUnlockingAtLevelList.RemoveAt(index);
                        stats.RearrangePerkUnlockingList();
                    }
                }

                startX = cachedX;
            }

            return(startY + spaceY + 5);
        }
Esempio n. 8
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            Rect marchingRect = new Rect(position.x, position.y, position.width, EditorGUIUtility.singleLineHeight);

            SerializedProperty itemProperty              = property.FindPropertyRelative("RewardTemplate");
            SerializedProperty minProperty               = property.FindPropertyRelative("MinCount");
            SerializedProperty maxProperty               = property.FindPropertyRelative("MaxCount");
            SerializedProperty prefixProperty            = property.FindPropertyRelative("Prefix");
            SerializedProperty suffixProperty            = property.FindPropertyRelative("Suffix");
            SerializedProperty modifiersProperty         = property.FindPropertyRelative("Modifiers");
            SerializedProperty overridePrefixProperty    = property.FindPropertyRelative("OverridePrefix");
            SerializedProperty overrideSuffixProperty    = property.FindPropertyRelative("OverrideSuffix");
            SerializedProperty overrideModifiersProperty = property.FindPropertyRelative("OverrideModifiers");

            Rect itemRect    = new Rect(marchingRect.x + FoldoutIndent, marchingRect.y, (marchingRect.width - countWidth * 2.0f) - FoldoutIndent, marchingRect.height);
            Rect foldoutRect = new Rect(itemRect.x, itemRect.y, 10, marchingRect.height);

            foldoutRect.xMax = EditorGUI.IndentedRect(itemRect).xMin + 7;

            Rect minRect = new Rect(itemRect.xMax, marchingRect.y, countWidth, marchingRect.height);
            Rect maxRect = new Rect(minRect.xMax, marchingRect.y, countWidth, marchingRect.height);

            ItemTemplate template = (ItemTemplate)itemProperty.objectReferenceValue;

            if (template != null && template.StackSize == 1)
            {
                property.isExpanded = EditorGUI.Foldout(foldoutRect, property.isExpanded, "", false);
            }

            EditorGUI.PropertyField(itemRect, itemProperty, GUIContent.none, false);

            int indent = EditorGUI.indentLevel;

            EditorGUI.indentLevel = 0;

            if (template != null)
            {
                EditorGUI.PropertyField(minRect, minProperty, GUIContent.none, false);
                EditorGUI.PropertyField(maxRect, maxProperty, GUIContent.none, false);

                maxProperty.intValue = Mathf.Max(1, maxProperty.intValue);
                minProperty.intValue = Mathf.Min(Mathf.Max(1, minProperty.intValue), maxProperty.intValue);
            }
            else
            {
                EditorGUI.BeginDisabledGroup(true);

                EditorGUI.DelayedIntField(minRect, GUIContent.none, 0);
                EditorGUI.DelayedIntField(maxRect, GUIContent.none, 0);

                EditorGUI.EndDisabledGroup();
            }
            EditorGUI.indentLevel = indent;

            if (property.isExpanded && template != null && template.StackSize == 1)
            {
                int dropdownOriginalIndent = EditorGUI.indentLevel;
                EditorGUI.indentLevel = 0;

                marchingRect.y += marchingRect.height + EditorGUIUtility.standardVerticalSpacing + INNER_SPACING + OUTER_SPACING;

                float modifiersHeight = EditorGUI.GetPropertyHeight(modifiersProperty);

                EditorGUI.indentLevel += 1;
                Rect backgroundIndent = EditorGUI.IndentedRect(marchingRect);
                EditorGUI.indentLevel -= 1;

                EditorGUI.indentLevel += 2;
                Rect indentRect = EditorGUI.IndentedRect(marchingRect);
                EditorGUI.indentLevel -= 2;

                if (overrideModifiersProperty.boolValue)
                {
                    EditorGUI.HelpBox(new Rect(backgroundIndent.x, backgroundIndent.y - INNER_SPACING, backgroundIndent.width,
                                               (EditorGUIUtility.standardVerticalSpacing * 2) + EditorGUIUtility.singleLineHeight + modifiersHeight +
                                               (INNER_SPACING * 2)),
                                      "", MessageType.None);
                }
                else
                {
                    EditorGUI.HelpBox(new Rect(backgroundIndent.x, backgroundIndent.y - INNER_SPACING, backgroundIndent.width,
                                               (EditorGUIUtility.standardVerticalSpacing * 2) + (EditorGUIUtility.singleLineHeight * 2) +
                                               (INNER_SPACING * 2)),
                                      "", MessageType.None);
                }

                Rect prefixToggleRect = new Rect(indentRect.x - 10, indentRect.y, EditorGUIUtility.singleLineHeight, indentRect.height);
                Rect prefixRect       = new Rect(prefixToggleRect.xMax, indentRect.y, (indentRect.width * 0.5f) - EditorGUIUtility.singleLineHeight, indentRect.height);

                Rect suffixToggleRect = new Rect(prefixRect.xMax, indentRect.y, EditorGUIUtility.singleLineHeight, indentRect.height);
                Rect suffixRect       = new Rect(suffixToggleRect.xMax, indentRect.y, prefixRect.width, indentRect.height);

                int originalIndent = EditorGUI.indentLevel;
                EditorGUI.indentLevel = 0;

                overridePrefixProperty.boolValue = !EditorGUI.Toggle(prefixToggleRect, !overridePrefixProperty.boolValue);
                if (overridePrefixProperty.boolValue)
                {
                    EditorGUI.PropertyField(prefixRect, prefixProperty, GUIContent.none);
                }
                else
                {
                    EditorGUI.LabelField(prefixRect, "Default Prefix");
                }


                overrideSuffixProperty.boolValue = !EditorGUI.Toggle(suffixToggleRect, !overrideSuffixProperty.boolValue);
                if (overrideSuffixProperty.boolValue)
                {
                    EditorGUI.PropertyField(suffixRect, suffixProperty, GUIContent.none);
                }
                else
                {
                    EditorGUI.LabelField(suffixRect, "Default Suffix");
                }


                EditorGUI.indentLevel = originalIndent;

                marchingRect.y += marchingRect.height + EditorGUIUtility.standardVerticalSpacing;

                marchingRect.height = modifiersHeight;
                marchingRect.height = EditorGUIUtility.standardVerticalSpacing;

                EditorGUI.indentLevel += 2;
                indentRect             = EditorGUI.IndentedRect(marchingRect);

                Rect modifiersToggleRect = new Rect(indentRect.x - 10, indentRect.y, EditorGUIUtility.singleLineHeight, EditorGUIUtility.singleLineHeight);
                Rect modifiersRect       = new Rect(modifiersToggleRect.xMax + 12, modifiersToggleRect.y,
                                                    marchingRect.xMax - (modifiersToggleRect.xMax + 18), modifiersHeight);

                EditorGUI.indentLevel -= 2;
                originalIndent         = EditorGUI.indentLevel;
                EditorGUI.indentLevel  = 0;
                overrideModifiersProperty.boolValue = !EditorGUI.Toggle(modifiersToggleRect, !overrideModifiersProperty.boolValue);

                if (overrideModifiersProperty.boolValue)
                {
                    marchingRect.y += marchingRect.height + EditorGUIUtility.standardVerticalSpacing;

                    EditorGUI.PropertyField(modifiersRect, modifiersProperty, true);
                }
                else
                {
                    EditorGUI.LabelField(new Rect(modifiersRect.x - 12, modifiersRect.y,
                                                  modifiersRect.width, modifiersRect.height), "Default Modifiers");
                }
                EditorGUI.indentLevel = originalIndent;

                EditorGUI.indentLevel = dropdownOriginalIndent;
            }
            else
            {
                prefixProperty.objectReferenceValue = null;
                suffixProperty.objectReferenceValue = null;
                modifiersProperty.ClearArray();
            }
        }
        void PrefInspectorGUI(TreeNode node, Rect rect, string key, PlayerPrefGUIType guiType)
        {
            EditorGUIUtility.labelWidth = 150F;

            object value = playerPrefCache[key];

            switch (value)
            {
            case int i:
                DrawIntField(rect, i);
                break;

            case float f:
                DrawFloatField(rect, f);
                break;

            case string str:
                DrawStringField(rect, str);
                break;

            default:
                break;
            }


            void DrawIntField(Rect r, int i)
            {
                using (var ch = new EditorGUI.ChangeCheckScope())
                {
                    if (guiType == PlayerPrefGUIType.Toggle)
                    {
                        bool b = (i == 1);
                        b = EditorGUI.Toggle(r, GUIContent.none, b);
                        if (ch.changed)
                        {
                            i = b ? 1 : 0;
                            playerPrefCache[key] = i;
                            node.displayName     = $"{key}";
                            PlayerPrefs.SetInt(key, i);
                            PlayerPrefs.Save();
                        }
                    }
                    else
                    {
                        i = EditorGUI.DelayedIntField(r, GUIContent.none, i);
                        if (ch.changed)
                        {
                            playerPrefCache[key] = i;
                            node.displayName     = $"{key}";
                            PlayerPrefs.SetInt(key, i);
                            PlayerPrefs.Save();
                        }
                    }
                }
            }

            void DrawFloatField(Rect r, float f)
            {
                using (var ch = new EditorGUI.ChangeCheckScope())
                {
                    if (guiType == PlayerPrefGUIType.Slider01)
                    {
                        f = EditorGUI.Slider(r, GUIContent.none, f, 0F, 1F);
                    }
                    else
                    {
                        f = EditorGUI.DelayedFloatField(r, GUIContent.none, f);
                    }
                    if (ch.changed)
                    {
                        playerPrefCache[key] = f;
                        node.displayName     = $"{key}";
                        PlayerPrefs.SetFloat(key, f);
                        PlayerPrefs.Save();
                    }
                }
            }

            void DrawStringField(Rect r, string str)
            {
                using (var ch = new EditorGUI.ChangeCheckScope())
                {
                    str = EditorGUI.DelayedTextField(r, GUIContent.none, str);
                    if (ch.changed)
                    {
                        playerPrefCache[key] = str;
                        node.displayName     = $"{key}";
                        PlayerPrefs.SetString(key, str);
                        PlayerPrefs.Save();
                    }
                }
            }
        }
        private static float DrawSettings(Rect position, SerializedProperty property, SerializedProperty collection)
        {
            var listState = ListStates[CollectionDisplay.GetFullPath(collection)];

            if (!listState.EditingSettings)
            {
                return(0);
            }

            Rect startPosition = position;

            position.xMin -= 6;
            position.xMax += 6;

            PackageSettings.ViewSettings settings        = PackageSettings.Settings.GetListSettings(collection);
            PackageSettings.ViewSettings defaultSettings = PackageSettings.Settings.DefaultListSettings;
            int pageSize = (settings == null) ? defaultSettings.ItemsPerPage : settings.ItemsPerPage;

            position.xMin += 7;
            position.xMax -= 7;
            position.y    += 4;

            position.height = EditorStyles.boldLabel.CalcHeight(new GUIContent("List Settings"), position.width);
            UnityEngine.GUI.Label(position, new GUIContent("List Settings"), EditorStyles.boldLabel);
            position.y += position.height;

            bool usePages    = (settings == null) ? defaultSettings.UsePages : settings.UsePages;
            bool newUsePages = EditorGUI.Toggle(position, "Use Page System", usePages);

            position.y += position.height;
            if (usePages != newUsePages)
            {
                if (settings == null)
                {
                    settings = PackageSettings.Settings.AddNewSettings(collection);
                }

                settings.UsePages     = newUsePages;
                listState.CurrentPage = 0;
                EditorUtility.SetDirty(PackageSettings.Settings);
            }

            float fieldHeight = EditorStyles.textField.fixedHeight;

            position.height = EditorGUIUtility.singleLineHeight;
            EditorStyles.textField.fixedHeight = position.height;
            if (newUsePages)
            {
                int newPageSize = EditorGUI.DelayedIntField(position, "Items Per Page", pageSize);
                if (newPageSize < 1)
                {
                    newPageSize = Mathf.Clamp(newPageSize, 1, 100);
                }

                if (newPageSize != pageSize)
                {
                    if (settings == null)
                    {
                        settings = PackageSettings.Settings.AddNewSettings(collection);
                    }

                    settings.ItemsPerPage = newPageSize;
                    listState.CurrentPage = 0;
                    EditorUtility.SetDirty(PackageSettings.Settings);
                }
                position.y += position.height + 4;
            }

            Color settingsColor = (settings == null) ? defaultSettings.Color : settings.Color;
            Color newColor      = EditorGUI.ColorField(position, "List Color", settingsColor);

            if (newColor != settingsColor)
            {
                if (settings == null)
                {
                    settings = PackageSettings.Settings.AddNewSettings(collection);
                }

                settings.Color = newColor;
                EditorUtility.SetDirty(PackageSettings.Settings);
            }
            position.y += position.height + 4;

            EditorStyles.textField.fixedHeight = fieldHeight;
            position.height = 2;
            UnityEngine.GUI.DrawTexture(position, dividerTexture);
            position.y += position.height + 2;
            return(position.y - startPosition.y);
        }
        private void DrawPoints()
        {
            var   points = spectrum.points;
            int   lines  = points.Count > 0 ? points.Count + 2 : 1;
            float height = EditorGUIUtility.singleLineHeight * lines;
            Rect  r1     = EditorGUILayout.GetControlRect(true, height);

            r1.width -= rightMargin;
            r1.height = EditorGUIUtility.singleLineHeight;

            {
                int oldCount = points.Count;
                int newCount = EditorGUI.DelayedIntField(r1, "Size", oldCount);
                r1.y += r1.height;

                if (newCount < points.Count)
                {
                    points.RemoveRange(newCount, oldCount - newCount);
                    Undo.SetCurrentGroupName("Points Removed");
                    GUI.changed = true;
                }
                else if (newCount > oldCount)
                {
                    if (newCount > points.Capacity)
                    {
                        points.Capacity = newCount;
                    }

                    for (int i = oldCount; i < newCount; i++)
                    {
                        points.Add(new Point(125 * (1 << i)));
                    }

                    Undo.SetCurrentGroupName("Points Added");
                    GUI.changed = true;
                }
            }

            if (points.Count > 0)
            {
                Rect r2 = new Rect(r1.xMax + 9, r1.y + r1.height * 1.125f, 24, r1.height * .75f);

                r1.width /= 2;
                EditorGUI.LabelField(r1, "Frequency");
                r1.x += r1.width;
                EditorGUI.LabelField(r1, "Data");
                r1.x -= r1.width;
                r1.y += r1.height;

                for (int i = 0; i < points.Count; i++)
                {
                    points[i].frequency = EditorGUI.FloatField(r1, points[i].frequency);
                    points[i].frequency = Mathf.Clamp(points[i].frequency, 0f, cutoff);
                    r1.x          += r1.width;
                    points[i].data = EditorGUI.FloatField(r1, points[i].data);
                    points[i].data = Mathf.Clamp01(points[i].data);
                    r1.x          -= r1.width;
                    r1.y          += r1.height;

                    if (GUI.Button(r2, "–"))
                    {
                        RemovePointAt(i);
                        break;
                    }

                    r2.y += r1.height;
                }
            }
        }
Esempio n. 12
0
        public static void ReorderableList <T>(ref List <T> list, string label, Action <Rect, int> onDrawItem = null, UnityEngine.Object undoContext = null, int buttonSize = 25)
        {
            var threeButton = buttonSize * 3;

            using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox)) {
                var headerRect = EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField("");
                if (!string.IsNullOrEmpty(label))
                {
                    EditorGUI.LabelField(LeftAlign(headerRect, headerRect.width - threeButton), label, EditorStyles.boldLabel);
                }
                var newCount = EditorGUI.DelayedIntField(RightAlign(headerRect, threeButton), list.Count);
                if (newCount < 0)
                {
                    newCount = 0;
                }

                if (newCount != list.Count)
                {
                    if (undoContext != null)
                    {
                        Undo.RecordObject(undoContext, "Changed list count");
                    }
                    if (newCount > list.Count)
                    {
                        while (list.Count < newCount)
                        {
                            list.Add(list.Count == 0 ? default : list[list.Count - 1]);
                        }
                    }
                    else
                    {
                        while (list.Count > newCount)
                        {
                            list.RemoveAt(list.Count - 1);
                        }
                    }
                }
                EditorGUILayout.EndHorizontal();

                for (var i = 0; i < list.Count; i++)
                {
                    var rect = EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.LabelField("");
                    onDrawItem?.Invoke(LeftAlign(rect, rect.width - threeButton), i);
                    if (i > 0)
                    {
                        if (GUI.Button(RightAlign(rect, buttonSize, -buttonSize * 2f), "▲"))
                        {
                            if (undoContext != null)
                            {
                                Undo.RecordObject(undoContext, "Reordered list");
                            }
                            var item = list[i - 1];
                            list[i - 1] = list[i];
                            list[i]     = item;
                        }
                    }

                    if (GUI.Button(RightAlign(rect, buttonSize, -buttonSize), "X"))
                    {
                        if (undoContext != null)
                        {
                            Undo.RecordObject(undoContext, "Removed list item");
                        }
                        list.RemoveAt(i);
                    }

                    if (i < list.Count - 1)
                    {
                        if (GUI.Button(RightAlign(rect, buttonSize), "▼"))
                        {
                            if (undoContext != null)
                            {
                                Undo.RecordObject(undoContext, "Reordered list");
                            }
                            var item = list[i];
                            list[i]     = list[i + 1];
                            list[i + 1] = item;
                        }
                    }

                    EditorGUILayout.EndHorizontal();
                }

                var footerRect = EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField("");
                if (GUI.Button(RightAlign(footerRect, threeButton), "+"))
                {
                    if (undoContext != null)
                    {
                        Undo.RecordObject(undoContext, "Added list item");
                    }
                    list.Add(default);
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            SerializedProperty prop_BaseGlyphID          = property.FindPropertyRelative("m_BaseMarkGlyphID");
            SerializedProperty prop_BaseGlyphAnchorPoint = property.FindPropertyRelative("m_BaseMarkGlyphAnchorPoint");

            SerializedProperty prop_MarkGlyphID          = property.FindPropertyRelative("m_CombiningMarkGlyphID");
            SerializedProperty prop_MarkAdjustmentRecord = property.FindPropertyRelative("m_CombiningMarkPositionAdjustment");

            position.yMin += 2;

            float width   = position.width / 2;
            float padding = 5.0f;

            Rect rect;

            isEditingEnabled = GUI.enabled;
            isSelectable     = label.text == "Selectable" ? true : false;

            if (isSelectable)
            {
                GUILayoutUtility.GetRect(position.width, 75);
            }
            else
            {
                GUILayoutUtility.GetRect(position.width, 55);
            }

            GUIStyle style = new GUIStyle(EditorStyles.label)
            {
                richText = true
            };

            // Base Glyph
            GUI.enabled = isEditingEnabled;
            if (isSelectable)
            {
                float labelWidth = GUI.skin.label.CalcSize(new GUIContent("ID: " + prop_BaseGlyphID.intValue)).x;

                if (!isEditingEnabled)
                {
                    EditorGUI.LabelField(new Rect(position.x + (64 - labelWidth) / 2, position.y + 60, 64f, 18f), new GUIContent("ID: <color=#FFFF80>" + prop_BaseGlyphID.intValue + "</color>"), style);
                }
                else
                {
                    EditorGUI.BeginChangeCheck();
                    EditorGUIUtility.labelWidth = 25f;
                    EditorGUI.DelayedIntField(new Rect(position.x + (64 - labelWidth) / 2, position.y + 60, 64, 18), prop_BaseGlyphID, new GUIContent("ID:"));
                    if (EditorGUI.EndChangeCheck())
                    {
                        FontAsset fontAsset = property.serializedObject.targetObject as FontAsset;
                        if (fontAsset != null)
                        {
                            property.serializedObject.ApplyModifiedProperties();
                            fontAsset.ReadFontAssetDefinition();
                            TextEventManager.ON_FONT_PROPERTY_CHANGED(true, fontAsset);
                        }
                    }
                }

                GUI.enabled = isEditingEnabled;
                EditorGUIUtility.labelWidth = 30f;

                rect = new Rect(position.x + 70, position.y + 10, (width - 70) - padding, 18);
                EditorGUI.PropertyField(rect, prop_BaseGlyphAnchorPoint.FindPropertyRelative("m_XCoordinate"), new GUIContent("X:"));

                rect.y += 20;
                EditorGUI.PropertyField(rect, prop_BaseGlyphAnchorPoint.FindPropertyRelative("m_YCoordinate"), new GUIContent("Y:"));

                DrawGlyph((uint)prop_BaseGlyphID.intValue, new Rect(position.x, position.y, position.width, position.height), property);
            }

            // Mark Glyph
            GUI.enabled = isEditingEnabled;
            if (isSelectable)
            {
                float labelWidth = GUI.skin.label.CalcSize(new GUIContent("ID: " + prop_MarkGlyphID.intValue)).x;

                if (!isEditingEnabled)
                {
                    EditorGUI.LabelField(new Rect(position.width / 2 + 20 + (64 - labelWidth) / 2, position.y + 60, 64f, 18f), new GUIContent("ID: <color=#FFFF80>" + prop_MarkGlyphID.intValue + "</color>"), style);
                }
                else
                {
                    EditorGUI.BeginChangeCheck();
                    EditorGUIUtility.labelWidth = 25f;
                    EditorGUI.DelayedIntField(new Rect(position.width / 2 + 20 + (64 - labelWidth) / 2, position.y + 60, 64, 18), prop_MarkGlyphID, new GUIContent("ID:"));
                    if (EditorGUI.EndChangeCheck())
                    {
                        FontAsset fontAsset = property.serializedObject.targetObject as FontAsset;
                        if (fontAsset != null)
                        {
                            property.serializedObject.ApplyModifiedProperties();
                            fontAsset.ReadFontAssetDefinition();
                            TextEventManager.ON_FONT_PROPERTY_CHANGED(true, fontAsset);
                        }
                    }
                }

                GUI.enabled = isEditingEnabled;
                EditorGUIUtility.labelWidth = 30f;

                rect = new Rect(position.width / 2 + 20 + 70, position.y + 10, (width - 70) - padding, 18);
                EditorGUI.PropertyField(rect, prop_MarkAdjustmentRecord.FindPropertyRelative("m_XPositionAdjustment"), new GUIContent("X:"));

                rect.y += 20;
                EditorGUI.PropertyField(rect, prop_MarkAdjustmentRecord.FindPropertyRelative("m_YPositionAdjustment"), new GUIContent("Y:"));

                DrawGlyph((uint)prop_MarkGlyphID.intValue, new Rect(position.width / 2 + 20, position.y, position.width, position.height), property);
            }
        }
Esempio n. 14
0
        // I've seen a lot of ugly methods in Unity source code, but this is just.. OMG
        // The method is identical to the original, only non-delayed fields are replaced with their delayed versions where possible.
        // For SerializedPropertyType.Integer, there is also a ternary expression instead of a single LongField because a version of DelayedLongField doesn't exist.
        public static bool DefaultPropertyFieldDelayed(Rect position, SerializedProperty property, GUIContent label)
        {
            label = EditorGUI.BeginPropertyInternal(position, label, property);

            SerializedPropertyType type = property.propertyType;

            bool childrenAreExpanded = false;

            // Should we inline? All one-line vars as well as Vector2, Vector3, Rect and Bounds properties are inlined.
            if (!EditorGUI.HasVisibleChildFields(property))
            {
                switch (type)
                {
                case SerializedPropertyType.Integer:
                {
                    EditorGUI.BeginChangeCheck();

                    long newValue = property.longValue > Int32.MaxValue
                            ? EditorGUI.LongField(position, label, property.longValue)
                            : EditorGUI.DelayedIntField(position, label, property.intValue);

                    if (EditorGUI.EndChangeCheck())
                    {
                        property.longValue = newValue;
                    }
                    break;
                }

                case SerializedPropertyType.Float:
                {
                    EditorGUI.BeginChangeCheck();

                    // Necessary to check for float type to get correct string formatting for float and double.
                    bool   isFloat  = property.type == "float";
                    double newValue = isFloat ? EditorGUI.DelayedFloatField(position, label, property.floatValue) :
                                      EditorGUI.DelayedDoubleField(position, label, property.doubleValue);
                    if (EditorGUI.EndChangeCheck())
                    {
                        property.doubleValue = newValue;
                    }
                    break;
                }

                case SerializedPropertyType.String:
                {
                    EditorGUI.BeginChangeCheck();
                    string newValue = EditorGUI.DelayedTextField(position, label, property.stringValue);
                    if (EditorGUI.EndChangeCheck())
                    {
                        property.stringValue = newValue;
                    }
                    break;
                }

                case SerializedPropertyType.Boolean:
                {
                    EditorGUI.BeginChangeCheck();
                    bool newValue = EditorGUI.Toggle(position, label, property.boolValue);
                    if (EditorGUI.EndChangeCheck())
                    {
                        property.boolValue = newValue;
                    }
                    break;
                }

                case SerializedPropertyType.Color:
                {
                    EditorGUI.BeginChangeCheck();
                    Color newColor = EditorGUI.ColorField(position, label, property.colorValue);
                    if (EditorGUI.EndChangeCheck())
                    {
                        property.colorValue = newColor;
                    }
                    break;
                }

                case SerializedPropertyType.ArraySize:
                {
                    EditorGUI.BeginChangeCheck();
                    int newValue = EditorGUI.ArraySizeField(position, label, property.intValue, EditorStyles.numberField);
                    if (EditorGUI.EndChangeCheck())
                    {
                        property.intValue = newValue;
                    }
                    break;
                }

                case SerializedPropertyType.FixedBufferSize:
                {
                    EditorGUI.DelayedIntField(position, label, property.intValue);
                    break;
                }

                case SerializedPropertyType.Enum:
                {
                    EditorGUI.EnumPopup(position, property, label);
                    break;
                }

                case SerializedPropertyType.ObjectReference:
                {
                    EditorGUI.ObjectFieldInternal(position, property, null, label, EditorStyles.objectField);
                    break;
                }

                case SerializedPropertyType.LayerMask:
                {
                    EditorGUI.LayerMaskField(position, property, label);
                    break;
                }

                case SerializedPropertyType.Character:
                {
                    char[] value = { (char)property.intValue };

                    bool wasChanged = GUI.changed;
                    GUI.changed = false;
                    string newValue = EditorGUI.DelayedTextField(position, label, new string(value));
                    if (GUI.changed)
                    {
                        if (newValue.Length == 1)
                        {
                            property.intValue = newValue[0];
                        }
                        // Value didn't get changed after all
                        else
                        {
                            GUI.changed = false;
                        }
                    }
                    GUI.changed |= wasChanged;
                    break;
                }

                case SerializedPropertyType.AnimationCurve:
                {
                    int id = GUIUtility.GetControlID(EditorGUI.s_CurveHash, FocusType.Keyboard, position);
                    EditorGUI.DoCurveField(EditorGUI.PrefixLabel(position, id, label), id, null, EditorGUI.kCurveColor, new Rect(), property);
                    break;
                }

                case SerializedPropertyType.Gradient:
                {
                    int id = GUIUtility.GetControlID(EditorGUI.s_CurveHash, FocusType.Keyboard, position);
                    EditorGUI.DoGradientField(EditorGUI.PrefixLabel(position, id, label), id, null, property, false, ColorSpace.Gamma);
                    break;
                }

                case SerializedPropertyType.Vector3:
                {
                    EditorGUI.Vector3Field(position, property, label);
                    break;
                }

                case SerializedPropertyType.Vector4:
                {
                    EditorGUI.Vector4Field(position, property, label);
                    break;
                }

                case SerializedPropertyType.Vector2:
                {
                    EditorGUI.Vector2Field(position, property, label);
                    break;
                }

                case SerializedPropertyType.Vector2Int:
                {
                    EditorGUI.Vector2IntField(position, property, label);
                    break;
                }

                case SerializedPropertyType.Vector3Int:
                {
                    EditorGUI.Vector3IntField(position, property, label);
                    break;
                }

                case SerializedPropertyType.Rect:
                {
                    EditorGUI.RectField(position, property, label);
                    break;
                }

                case SerializedPropertyType.RectInt:
                {
                    EditorGUI.RectIntField(position, property, label);
                    break;
                }

                case SerializedPropertyType.Bounds:
                {
                    EditorGUI.BoundsField(position, property, label);
                    break;
                }

                case SerializedPropertyType.BoundsInt:
                {
                    EditorGUI.BoundsIntField(position, property, label);
                    break;
                }

                default:
                {
                    int genericID = GUIUtility.GetControlID(EditorGUI.s_GenericField, FocusType.Keyboard, position);
                    EditorGUI.PrefixLabel(position, genericID, label);
                    break;
                }
                }
            }
            // Handle Foldout
            else
            {
                Event tempEvent = new Event(Event.current);

                // Handle the actual foldout first, since that's the one that supports keyboard control.
                // This makes it work more consistent with PrefixLabel.
                childrenAreExpanded = property.isExpanded;

                bool newChildrenAreExpanded = childrenAreExpanded;
                using (new EditorGUI.DisabledScope(!property.editable))
                {
                    GUIStyle foldoutStyle = (DragAndDrop.activeControlID == -10) ? EditorStyles.foldoutPreDrop : EditorStyles.foldout;
                    newChildrenAreExpanded = EditorGUI.Foldout(position, childrenAreExpanded, EditorGUI.s_PropertyFieldTempContent, true, foldoutStyle);
                }


                if (childrenAreExpanded && property.isArray && property.arraySize > property.serializedObject.maxArraySizeForMultiEditing && property.serializedObject.isEditingMultipleObjects)
                {
                    Rect boxRect = position;
                    boxRect.xMin += EditorGUIUtility.labelWidth - EditorGUI.indent;

                    EditorGUI.s_ArrayMultiInfoContent.text = EditorGUI.s_ArrayMultiInfoContent.tooltip = string.Format(EditorGUI.s_ArrayMultiInfoFormatString, property.serializedObject.maxArraySizeForMultiEditing);
                    EditorGUI.LabelField(boxRect, GUIContent.none, EditorGUI.s_ArrayMultiInfoContent, EditorStyles.helpBox);
                }

                if (newChildrenAreExpanded != childrenAreExpanded)
                {
                    // Recursive set expanded
                    if (Event.current.alt)
                    {
                        EditorGUI.SetExpandedRecurse(property, newChildrenAreExpanded);
                    }
                    // Expand one element only
                    else
                    {
                        property.isExpanded = newChildrenAreExpanded;
                    }
                }
                childrenAreExpanded = newChildrenAreExpanded;


                // Check for drag & drop events here, to add objects to an array by dragging to the foldout.
                // The event may have already been used by the Foldout control above, but we want to also use it here,
                // so we use the event copy we made prior to calling the Foldout method.

                // We need to use last s_LastControlID here to ensure we do not break duplicate functionality (fix for case 598389)
                // If we called GetControlID here s_LastControlID would be incremented and would not longer be in sync with GUIUtililty.keyboardFocus that
                // is used for duplicating (See DoPropertyFieldKeyboardHandling)
                int id = EditorGUIUtility.s_LastControlID;
                switch (tempEvent.type)
                {
                case EventType.DragExited:
                    if (GUI.enabled)
                    {
                        HandleUtility.Repaint();
                    }

                    break;

                case EventType.DragUpdated:
                case EventType.DragPerform:

                    if (position.Contains(tempEvent.mousePosition) && GUI.enabled)
                    {
                        Object[] references = DragAndDrop.objectReferences;

                        // Check each single object, so we can add multiple objects in a single drag.
                        Object[] oArray        = new Object[1];
                        bool     didAcceptDrag = false;
                        foreach (Object o in references)
                        {
                            oArray[0] = o;
                            Object validatedObject = EditorGUI.ValidateObjectFieldAssignment(oArray, null, property, EditorGUI.ObjectFieldValidatorOptions.None);
                            if (validatedObject != null)
                            {
                                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                                if (tempEvent.type == EventType.DragPerform)
                                {
                                    property.AppendFoldoutPPtrValue(validatedObject);
                                    didAcceptDrag = true;
                                    DragAndDrop.activeControlID = 0;
                                }
                                else
                                {
                                    DragAndDrop.activeControlID = id;
                                }
                            }
                        }
                        if (didAcceptDrag)
                        {
                            GUI.changed = true;
                            DragAndDrop.AcceptDrag();
                        }
                    }
                    break;
                }
            }

            EditorGUI.EndProperty();

            return(childrenAreExpanded);
        }
        void GPUCacheSizeOverridesGUI(Rect rect, int settingIdx, SerializedProperty settingListProperty, GPUCacheSettingSRP[] settingList)
        {
            var cacheSizeOverrideProperty = settingListProperty.GetArrayElementAtIndex(settingIdx);
            var cacheSizeOverride         = settingList[settingIdx];

#if ENABLE_VIRTUALTEXTURES
            List <GraphicsFormat> availableFormats = new List <GraphicsFormat>(EditorHelpers.QuerySupportedFormats());
            // None is used for a default cache size.
            availableFormats.Add(GraphicsFormat.None);

            RemoveOverriddenFormats(availableFormats, settingList);

            // Group formats
            Dictionary <string, List <string> > formatGroups = new Dictionary <string, List <string> >();
            foreach (GraphicsFormat graphicsFormat in availableFormats)
            {
                GraphicsFormatToFormatAndChannelTransformString(graphicsFormat, out var format, out var channelTransform);
                if (!formatGroups.ContainsKey(format))
                {
                    formatGroups.Add(format, new List <string>());
                }
                formatGroups[format].Add(channelTransform);
            }
#endif

            GraphicsFormat serializedFormat = (GraphicsFormat)cacheSizeOverrideProperty.FindPropertyRelative("format").intValue;
            GraphicsFormatToFormatAndChannelTransformString(serializedFormat, out string formatString, out string channelTransformString);


            // GUI Drawing

            float settingWidth = rect.width;

            float spacing = Math.Min(5, settingWidth * 0.02f);

            settingWidth -= 2 * spacing;

            float formatLabelWidth      = Math.Min(60, settingWidth * 0.25f);
            float formatWidth           = settingWidth * 0.3f;
            float channelTransformWidth = settingWidth * 0.25f;
            float sizeLabelWidth        = Math.Min(45, settingWidth * 0.2f);
            float sizeWidth             = settingWidth * 0.15f;

            // Format
            rect.width = formatLabelWidth;
            EditorGUI.LabelField(rect, s_Styles.gpuCacheSizeOverrideFormat);

            rect.position += new Vector2(formatLabelWidth, 0);
            rect.width     = formatWidth;
            if (EditorGUI.DropdownButton(rect, new GUIContent(formatString), FocusType.Keyboard))
            {
#if ENABLE_VIRTUALTEXTURES
                GenericMenu menu = new GenericMenu();
                foreach (string possibleFormat in formatGroups.Keys)
                {
                    string localFormat = possibleFormat;
                    menu.AddItem(new GUIContent(localFormat), formatString == localFormat, () =>
                    {
                        // Make sure the channelTransform is valid for the format.
                        List <string> formatGroup = formatGroups[localFormat];
                        if (formatGroup.FindIndex((string possibleChannelTransform) => { return(possibleChannelTransform == channelTransformString); }) == -1)
                        {
                            channelTransformString = formatGroup[0];
                        }

                        cacheSizeOverrideProperty.FindPropertyRelative("format").intValue = (int)FormatAndChannelTransformStringToGraphicsFormat(localFormat, channelTransformString);

                        serializedObject.ApplyModifiedProperties();
                    });
                }

                menu.ShowAsContext();
#endif
            }

            // Channel transform
            rect.position += new Vector2(formatWidth, 0);
            rect.width     = channelTransformWidth;

            List <string> possibleChannelTransforms = new List <string>();

#if ENABLE_VIRTUALTEXTURES
            if (formatGroups.ContainsKey(formatString))
            {
                possibleChannelTransforms = formatGroups[formatString];
            }
#endif

            EditorGUI.BeginDisabledGroup(possibleChannelTransforms.Count == 0);
            {
                if (serializedFormat != GraphicsFormat.None && EditorGUI.DropdownButton(rect, new GUIContent(channelTransformString), FocusType.Keyboard))
                {
#if ENABLE_VIRTUALTEXTURES
                    GenericMenu menu = new GenericMenu();
                    possibleChannelTransforms.Add(channelTransformString);
                    possibleChannelTransforms.Sort();

                    foreach (string possibleChannelTransform in possibleChannelTransforms)
                    {
                        string localChannelTransform = possibleChannelTransform;
                        menu.AddItem(new GUIContent(localChannelTransform), localChannelTransform == channelTransformString, () =>
                        {
                            GraphicsFormat format = FormatAndChannelTransformStringToGraphicsFormat(formatString, localChannelTransform);
                            cacheSizeOverrideProperty.FindPropertyRelative("format").intValue = (int)format;
                            serializedObject.ApplyModifiedProperties();
                        });
                    }

                    menu.ShowAsContext();
#endif
                }
            }
            EditorGUI.EndDisabledGroup();

            // Size
            rect.position += new Vector2(channelTransformWidth + spacing, 0);
            rect.width     = sizeLabelWidth;

            EditorGUI.LabelField(rect, s_Styles.gpuCacheSizeOverrideSize);

            rect.position += new Vector2(sizeLabelWidth, 0);
            rect.width     = sizeWidth;

            cacheSizeOverride.sizeInMegaBytes = (uint)Mathf.Max(GPUCacheSizeMinValue,
                                                                EditorGUI.DelayedIntField(rect, (int)cacheSizeOverride.sizeInMegaBytes));
            cacheSizeOverrideProperty.FindPropertyRelative("sizeInMegaBytes").intValue =
                (int)cacheSizeOverride.sizeInMegaBytes;
        }
        /// <summary>Draw multiple fields in a single line.</summary>
        /// <typeparam name="T">The type to render.</typeparam>
        /// <param name="position">The rect to use to draw the GUI.</param>
        /// <param name="subLabels">The labels for each sub value field.</param>
        /// <param name="values">The current values of the fields.</param>
        static void MultiField <T>(Rect position, GUIContent[] subLabels, T[] values)
            where T : struct
        {
            // The number of slots we need to fit into this rectangle
            var length = values.Length;

            // Let's compute the space allocated for every field including the label
            var num = position.width / (float)length;

            // Reset the indentation
            var indentLevel = EditorGUI.indentLevel;

            EditorGUI.indentLevel = 0;

            // Variable to keep track of the current pixel shift in the rectangle we were assigned for this whole section.
            float pixelShift = 0;

            // Loop through the levels
            for (var index = 0; index < values.Length; ++index)
            {
                // Let's first compute what is the width of the label of this scalable setting level
                // We make sure that the label doesn't go beyond the space available for this scalable setting level
                var labelWidth = Mathf.Clamp(CalcPrefixLabelWidth(subLabels[index], (GUIStyle)null), 0, num);

                // Draw the Label at the expected position
                EditorGUI.LabelField(new Rect(position.x + pixelShift, position.y, labelWidth, position.height), subLabels[index]);

                // We need to remove from the position the label size that we've just drawn and shift by it's length
                pixelShift += labelWidth;

                // The amount of space left for the field
                float spaceLeft = num - labelWidth;

                // If at least two pixels are left to draw this field, draw it, otherwise, skip
                if (spaceLeft > 2)
                {
                    // Define the rectangle for the field
                    var fieldSlot = new Rect(position.x + pixelShift, position.y, num - labelWidth, position.height);

                    // Draw the right field depending on its type.
                    if (typeof(T) == typeof(int))
                    {
                        values[index] = (T)(object)EditorGUI.DelayedIntField(fieldSlot, (int)(object)values[index]);
                    }
                    else if (typeof(T) == typeof(bool))
                    {
                        values[index] = (T)(object)EditorGUI.Toggle(fieldSlot, (bool)(object)values[index]);
                    }
                    else if (typeof(T) == typeof(float))
                    {
                        values[index] = (T)(object)EditorGUI.FloatField(fieldSlot, (float)(object)values[index]);
                    }
                    else if (typeof(T).IsEnum)
                    {
                        values[index] = (T)(object)EditorGUI.EnumPopup(fieldSlot, (Enum)(object)values[index]);
                    }
                    else
                    {
                        throw new ArgumentOutOfRangeException($"<{typeof(T)}> is not a supported type for multi field");
                    }
                }

                // Shift by the slot that was left for the field
                pixelShift += spaceLeft;
            }
            EditorGUI.indentLevel = indentLevel;
        }
Esempio n. 17
0
        private void DrawTileDataComponent(Rect tileDataComponentRectangle, ScriptedTile.Rule rule)
        {
            float componentPositionX = tileDataComponentRectangle.x;
            float fieldPositionY     = tileDataComponentRectangle.y;
            Rect  fieldRectangle;

            /*
             * Inicia o `fieldOrderNumber`.
             * Ele controla a quantidade de padding que cada Field precisa.
             * A quantidade de padding é baseada na ordem (1º, 2º, ...) do Field.
             */
            int fieldOrderNumber = UpdateFieldOrderNumber(0);

            fieldRectangle      = GetFieldRectangle("Game Object", componentPositionX, ref fieldPositionY, ref fieldOrderNumber, tileDataComponentRectangle, rule);
            rule.tileGameObject = EditorGUI.ObjectField(fieldRectangle, "", rule.tileGameObject, typeof(GameObject), false) as GameObject;

            fieldRectangle        = GetFieldRectangle("Collider Type", componentPositionX, ref fieldPositionY, ref fieldOrderNumber, tileDataComponentRectangle, rule);
            rule.tileColliderType = (Tile.ColliderType)EditorGUI.EnumPopup(fieldRectangle, rule.tileColliderType);

            fieldRectangle        = GetFieldRectangle("Sprite Output", componentPositionX, ref fieldPositionY, ref fieldOrderNumber, tileDataComponentRectangle, rule);
            rule.spriteOutputType = (ScriptedTile.RuleTileData.SpriteOutputType)EditorGUI.EnumPopup(fieldRectangle, rule.spriteOutputType);

            if (rule.spriteOutputType == ScriptedTile.RuleTileData.SpriteOutputType.Animation)
            {
                fieldRectangle      = GetFieldRectangle("Speed", componentPositionX, ref fieldPositionY, ref fieldOrderNumber, tileDataComponentRectangle, rule);
                rule.animationSpeed = EditorGUI.FloatField(fieldRectangle, rule.animationSpeed);
            }

            if (rule.spriteOutputType == ScriptedTile.RuleTileData.SpriteOutputType.Random)
            {
                fieldRectangle        = GetFieldRectangle("Noise", componentPositionX, ref fieldPositionY, ref fieldOrderNumber, tileDataComponentRectangle, rule);
                rule.perlinNoiseScale = EditorGUI.Slider(fieldRectangle, rule.perlinNoiseScale, 0.001f, 0.999f);

                fieldRectangle = GetFieldRectangle("Rotation", componentPositionX, ref fieldPositionY, ref fieldOrderNumber, tileDataComponentRectangle, rule);
                rule.randomSpriteRotationType = (ScriptedTile.Rule.RotationType)EditorGUI.EnumPopup(fieldRectangle, rule.randomSpriteRotationType);
            }

            // Lista de Sprites para a animação ou, para a randomização.
            if (rule.spriteOutputType != ScriptedTile.RuleTileData.SpriteOutputType.Single)
            {
                #region Sprites Fields.
                Rect spritesNumberLabelRectangle = new Rect(
                    componentPositionX,
                    fieldPositionY + GetFieldPaddingTopByFieldPositionY(fieldPositionY, fieldOrderNumber),
                    ReorderableListGUIDefaults.FieldWidth,
                    ReorderableListGUIDefaults.FieldHeight
                    );

                Rect spritesNumberFieldRectangle = new Rect(
                    componentPositionX + ReorderableListGUIDefaults.FieldWidth,
                    fieldPositionY + GetFieldPaddingTopByFieldPositionY(fieldPositionY, fieldOrderNumber),

                    /*
                     * `componentRectangle.width`: A largura do Field é proporcional a largura do element do ReorderableList,
                     * pois, `componentRectangle` é baseado no elementRectangle.
                     */
                    tileDataComponentRectangle.width - ReorderableListGUIDefaults.FieldWidth,
                    ReorderableListGUIDefaults.FieldHeight
                    );

                EditorGUI.BeginChangeCheck();

                GUI.Label(spritesNumberLabelRectangle, "Sprites");
                int spritesNumber = EditorGUI.DelayedIntField(spritesNumberFieldRectangle, rule.tileSprites.Length);

                /*
                 * Não há necessidade de ter mais que 500 Sprites por Rule.
                 * Um valor muito grande pode causar atrasos no Editor, por causa da quantidade de loops.
                 */
                spritesNumber = Mathf.Min(500, spritesNumber);

                // Modificar a lista de Sprites quando o Field acima (a quantidade de Sprites) for modificado.
                if (EditorGUI.EndChangeCheck())
                {
                    // Deve ter pelo menos um campo.
                    Array.Resize(ref rule.tileSprites, Mathf.Max(spritesNumber, 1));
                }

                fieldPositionY   = UpdateFieldPositionY(fieldPositionY);
                fieldOrderNumber = UpdateFieldOrderNumber(fieldOrderNumber);

                for (int spriteIndex = 0; spriteIndex < rule.tileSprites.Length; spriteIndex++)
                {
                    Rect spriteFieldRectangle = new Rect(
                        componentPositionX + ReorderableListGUIDefaults.FieldWidth,
                        fieldPositionY + GetFieldPaddingTopByFieldPositionY(fieldPositionY, fieldOrderNumber),

                        /*
                         * `componentRectangle.width`: A largura do Field é proporcional a largura do element do ReorderableList,
                         * pois, `componentRectangle` é baseado no elementRectangle.
                         */
                        tileDataComponentRectangle.width - ReorderableListGUIDefaults.FieldWidth,
                        ReorderableListGUIDefaults.FieldHeight
                        );

                    rule.tileSprites[spriteIndex] = EditorGUI.ObjectField(spriteFieldRectangle, rule.tileSprites[spriteIndex], typeof(Sprite), false) as Sprite;

                    fieldPositionY   = UpdateFieldPositionY(fieldPositionY);
                    fieldOrderNumber = UpdateFieldOrderNumber(fieldOrderNumber);
                }
                #endregion
            }
        }
Esempio n. 18
0
        public bool drawNodes(Dialogue asset, List <Node> inNodes, Vector2 inOffet)
        {
            if (asset == null || inNodes == null)
            {
                return(false);
            }

            offset = inOffet;

            bool changed = false;

            nodes = inNodes;

            Vector2 rootPos  = new Vector2(0, Screen.height * 0.5f);
            Rect    rootRect = new Rect(rootPos.x - offset.x - 39, rootPos.y - offset.y - 7, 38, 14);

            EditorGUI.DrawRect(new Rect(rootRect.x - 1, rootRect.y - 1, rootRect.width + 2, rootRect.height + 2), Color.black);
            EditorGUI.DrawRect(rootRect, new Color(0.75f, 0.75f, 0.75f));
            EditorGUI.LabelField(rootRect, "Root");

            if (nodes != null && nodes.Count != 0)
            {
                // Draw links between nodes first:
                for (int i = 0; i < nodes.Count; ++i)
                {
                    Node         node  = nodes[i];
                    DialogueNode dNode = node.node;

                    // Links from dialogue root:
                    if (node.rootId >= 0)
                    {
                        DialogueRoot root           = asset.rootNodes[node.rootId];
                        bool         rootConditions = !string.IsNullOrEmpty(root.conditions.keyword);
                        drawNodeLink(rootPos, node, i, 0, rootConditions);
                    }

                    // Links to response nodes:
                    if (dNode.responses != null)
                    {
                        for (int j = 0; j < dNode.responses.Length; ++j)
                        {
                            DialogueResponse resp    = dNode.responses[j];
                            Vector2          respPos = getResponsePosition(node, j);

                            // Draw short red lines to indicate a response is no linked to any node:
                            if (resp.nextNode == null)
                            {
                                respPos      -= offset;
                                Handles.color = Color.red;
                                Handles.DrawLine(respPos, respPos + Vector2.right * 32);
                                continue;
                            }

                            // Figure out the editor node representing the response's connected node asset:
                            Node targetNode = Node.Blank;
                            int  k          = 0;
                            for (k = 0; k < nodes.Count; ++k)
                            {
                                Node n = nodes[k];
                                if (n.node == resp.nextNode)
                                {
                                    targetNode = n;
                                    break;
                                }
                            }

                            // Draw link in a different color if conditions apply for the associated response:
                            bool hasConditions = !string.IsNullOrEmpty(resp.conditions.keyword);

                            // Draw a bezier curve starting at the response button and leading to the connected node:
                            drawNodeLink(respPos, targetNode, i, k, hasConditions);
                        }
                    }
                }

                // Draw the actual individual nodes:
                for (int i = 0; i < nodes.Count; ++i)
                {
                    Node node = nodes[i];
                    // If a node is null, mark it for later deletion:
                    if (node.node == null)
                    {
                        node.rootId = -1;
                        nodes[i]    = node;
                        continue;
                    }

                    bool isSelected = selected.node == node.node;
                    // Update drag&drop:
                    NodeAction actions = new NodeAction()
                    {
                        changed = false, selected = false, startDragDrop = false
                    };
                    if (isSelected && dragNDrop)
                    {
                        Vector2 mousePos = Event.current.mousePosition;
                        node.rect.x     = mousePos.x - 123 + offset.x;
                        node.rect.y     = mousePos.y - 5 + offset.y;
                        actions.changed = true;
                    }

                    // Round positions to whole numbers, 'cause without it the damn thing looks ugly as hell:
                    node.rect.x = Mathf.Round(node.rect.x);
                    node.rect.y = Mathf.Round(node.rect.y);

                    // Draw the node on screen:
                    actions = drawNode(ref node, isSelected, i);
                    // Raise the dirty flag if the node has been changed:
                    if (actions.changed)
                    {
                        nodes[i] = node;
                        changed  = true;
                    }
                    // Select the node if a related action was performed:
                    if (actions.selected)
                    {
                        setSelection(node);
                    }
                    // Start drag&drop of the node if a related action was performed:
                    if (actions.startDragDrop)
                    {
                        toggleDragNDrop();
                    }
                }

                // Draw response dropdown overlay:
                if (selectedResponseDropdown && selectedResponse >= 0 && selectedResponse < selected.node.responses.Length)
                {
                    Node             respNode  = selected;
                    DialogueNode     respDNode = respNode.node;
                    DialogueResponse resp      = respDNode.responses[selectedResponse];

                    const float w = 160;
                    const float h = 94;

                    Rect  respRect = respNode.rect;
                    float respPosY = Mathf.Round(respRect.y + 33 + (-respDNode.responses.Length * .5f + selectedResponse) * 17);
                    respRect = new Rect(respRect.x - offset.x + 138, respPosY - offset.y, w + 2, h + 2);

                    GUI.BeginGroup(respRect);

                    EditorGUI.DrawRect(new Rect(0, 0, w + 2, h + 2), Color.black);
                    EditorGUI.DrawRect(new Rect(1, 1, w, h), new Color(0.75f, 0.75f, 0.75f));

                    EditorGUI.LabelField(new Rect(2, 2, w, 16), string.Format("Edit response {0}:", selectedResponse));

                    // Button for creating a new node linked to this response:
                    if (GUI.Button(new Rect(2, 20, 78, 16), "New Node"))
                    {
                        if (createNewNode(asset, ref nodes))
                        {
                            int newNodeId = nodes.Count - 1;
                            if (createNodeLink(selected, selectedResponse, newNodeId))
                            {
                                //Debug.Log("Creating new node connected to selected node's response " + selectedResponse);
                                setSelection(nodes[newNodeId]);
                            }
                        }
                    }

                    // Button for removing the currently set link:
                    bool uiShowClearLink = selected.node.responses != null &&
                                           selectedResponse >= 0 &&
                                           selectedResponse < selected.node.responses.Length &&
                                           selected.node.responses[selectedResponse].nextNode == null;
                    EditorGUI.BeginDisabledGroup(uiShowClearLink);
                    if (GUI.Button(new Rect(82, 20, 78, 16), "Clear Link"))
                    {
                        //Debug.Log("Resetting response " + selectedResponse + " in selected node.");
                        createNodeLink(respNode, selectedResponse, -1);
                    }
                    EditorGUI.EndDisabledGroup();

                    // Button and input field for linking to a specific node using its displayed node ID:
                    if (GUI.Button(new Rect(2, 38, 128, 16), "Link to ID"))
                    {
                        createNodeLink(respNode, selectedResponse, responseTargetNodeId);
                        //Debug.Log("Connecting selected node's response " + selectedResponse + " to node " + responseTargetNodeId);
                    }
                    responseTargetNodeId = EditorGUI.DelayedIntField(new Rect(131, 38, 29, 16), responseTargetNodeId);

                    bool prevChanged = GUI.changed;
                    GUI.changed = false;

                    EditorGUI.LabelField(new Rect(2, 60, 34, 16), "Text");
                    resp.responseText = EditorGUI.DelayedTextField(new Rect(36, 60, w - 36, 16), resp.responseText);

                    EditorGUI.LabelField(new Rect(2, 78, 34, 16), "Cond");
                    resp.conditions.keyword = EditorGUI.DelayedTextField(new Rect(36, 78, w - 36, 16), resp.conditions.keyword);

                    if (GUI.changed)
                    {
                        EditorUtility.SetDirty(asset);
                    }
                    GUI.changed = GUI.changed || prevChanged;

                    GUI.EndGroup();
                }
            }

            return(changed);
        }
Esempio n. 19
0
        private float DrawAddPerkGained(float startX, float startY, LevelProgressionStats stats)
        {
            spaceX -= 65;

            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width + 30, height), "Add Perk Gained At lvl:", headerStyle);

            cont = new GUIContent(" - Level:", "");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);
            perkGainLvl = EditorGUI.DelayedIntField(new Rect(startX + spaceX, startY, widthS, height), perkGainLvl);
            perkGainLvl = Mathf.Clamp(perkGainLvl, 1, stats.levelCap);


            int perkIdx = perkGainID >= 0 ? TDSEditor.GetPerkIndex(perkGainID) : 0;

            cont = new GUIContent(" - Perk:", "Perk to be gained");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);

            perkIdx = EditorGUI.Popup(new Rect(startX + spaceX, startY, widthS + 65, height), perkIdx, perkLabel);
            if (perkIdx > 0)
            {
                perkGainID = perkDB.perkList[perkIdx - 1].ID;
            }
            else
            {
                perkGainID = -1;
            }

            spaceX += 65;


            if (perkGainID >= 0 && GUI.Button(new Rect(startX + 15, startY += spaceY + 2, spaceX + widthS - 15, height + 2), "Add Entry"))
            {
                PerkUnlockingAtLevel item = null;
                int index = 0;

                for (int i = 0; i < stats.perkUnlockingAtLevelList.Count; i++)
                {
                    if (stats.perkUnlockingAtLevelList[i].level == perkGainLvl)
                    {
                        item = stats.perkUnlockingAtLevelList[i];
                        break;
                    }

                    if (stats.perkUnlockingAtLevelList[i].level > perkGainLvl)
                    {
                        index += 1;
                    }
                }

                if (item != null)
                {
                    if (!item.perkIDList.Contains(perkGainID))
                    {
                        item.perkIDList.Add(perkGainID);
                    }
                }
                else
                {
                    item = new PerkUnlockingAtLevel(perkGainLvl);
                    item.perkIDList.Add(perkGainID);

                    stats.perkUnlockingAtLevelList.Insert(index, item);
                }

                perkGainID = -1;

                stats.RearrangePerkUnlockingList();
            }

            return(startY);
        }
Esempio n. 20
0
        private void DrawCompressionMethod()
        {
            BitsDeterminedBy btb = (BitsDeterminedBy)
                                   EditorGUI.EnumPopup(new Rect(ir.xMin + PADDING, line, labelwidth - 8, LINEHEIGHT), GUIContent.none, fc.BitsDeterminedBy);

            // IF we switched to pro - the btb value is actually the bits value, force a change to SetBits
            if (FC_ISPRO && btb >= 0)
            {
                fc.Bits = (int)btb;
            }

            else if (!FC_ISPRO && btb == BitsDeterminedBy.SetBits)            //.CustomBits)
            {
                // In case we went from pro to free... quietly set this back to non-custom.
                if (fc.BitsDeterminedBy != BitsDeterminedBy.SetBits)
                {
                    ProFeatureDialog("");
                }
                else
                {
                    fc.Bits = fc.Bits;
                }
            }
            else if (fc.BitsDeterminedBy != btb)
            {
                haschanged = true;
                Undo.RecordObject(p.serializedObject.targetObject, "Changed Crusher Bits Determined By");
                fc.BitsDeterminedBy = btb;
                p.serializedObject.Update();
            }

            float fieldleft  = paddedleft + labelwidth;
            float fieldwidth = paddedwidth - labelwidth;

            //const float labelW = 48f;
            const float inputW     = 50f;
            float       input2Left = paddedright - inputW;

            switch (fc.BitsDeterminedBy)
            {
            case BitsDeterminedBy.HalfFloat:
                break;

            case BitsDeterminedBy.Uncompressed:
                break;

            case BitsDeterminedBy.Disabled:
                break;

            case BitsDeterminedBy.Resolution:

                EditorGUI.LabelField(new Rect(rightinputsleft - 128, line, 128, LINEHEIGHT), new GUIContent(holdindent < 2 ? "Min resolution: 1/" : "Min res 1/"), miniLabelRight);

                uint res = (uint)EditorGUI.DelayedIntField(new Rect(input2Left, line - 1, inputW, LINEHEIGHT), GUIContent.none, (int)fc.Resolution);

                if (fc.Resolution != res)
                {
                    haschanged = true;
                    Undo.RecordObject(p.serializedObject.targetObject, "Changed Resolution value");
                    fc.Resolution = res;
                }

                break;

            case BitsDeterminedBy.Precision:

                EditorGUI.LabelField(new Rect(rightinputsleft - 128, line, 128, LINEHEIGHT), new GUIContent((holdindent < 2) ? "Min precision: " : "Min prec: "), miniLabelRight);
                float precision = EditorGUI.DelayedFloatField(new Rect(input2Left, line - 1, inputW, LINEHEIGHT), GUIContent.none, fc.Precision);

                if (fc.Precision != precision)
                {
                    haschanged = true;
                    Undo.RecordObject(p.serializedObject.targetObject, "Changed Precision value");
                    fc.Precision = (float)Math.Round(precision * 100000) / 100000;
                }

                break;

            default:

                if (FC_ISPRO && fc.BitsDeterminedBy == (BitsDeterminedBy.SetBits))
                {
                    EditorGUI.indentLevel = holdindent;
#if UNITY_2019_3_OR_NEWER
                    int bits = EditorGUI.IntSlider(new Rect(fieldleft, line, fieldwidth, LINEHEIGHT + 2), GUIContent.none, fc.Bits, 0, 32);
#else
                    int bits = EditorGUI.IntSlider(new Rect(fieldleft, line, fieldwidth, LINEHEIGHT), GUIContent.none, fc.Bits, 0, 32);
#endif
                    EditorGUI.indentLevel = 0;

                    if (fc.Bits != bits)
                    {
                        haschanged = true;
                        Undo.RecordObject(p.serializedObject.targetObject, "Changed Bits value");
                        fc.Bits = bits;
                    }
                    break;
                }

                float sliderleft  = ir.xMin + PADDING + labelwidth;                        // ir.xMin + PADDING + labelwidth;
                float sliderwidth = ir.width - PADDING - labelwidth - PADDING;             // - sliderleft - PADDING;

                GUI.enabled = false;
#if UNITY_2019_3_OR_NEWER
                EditorGUI.IntSlider(new Rect(sliderleft, line, sliderwidth, LINEHEIGHT + 2), GUIContent.none, (int)fc.BitsDeterminedBy, 0, 32);
#else
                EditorGUI.IntSlider(new Rect(sliderleft, line, sliderwidth, LINEHEIGHT), GUIContent.none, (int)fc.BitsDeterminedBy, 0, 32);
#endif
                //EditorGUI.IntSlider(new Rect(fieldleft, line, fieldwidth, LINEHEIGHT), GUIContent.none, (int)fc.BitsDeterminedBy, 0, 32);
                GUI.enabled = true;

                break;
            }

            line += COMPMTHD_HGHT;
        }
Esempio n. 21
0
        public override bool OnGUI()
        {
            if (!base.OnGUI())
            {
                return(true);
            }

            if (window == null)
            {
                Init();
            }

            if (Selection.activeGameObject != null)
            {
                selectedComponent = Selection.activeGameObject.GetComponent <PlayerProgression>();
            }
            else
            {
                selectedComponent = null;
            }

            Undo.RecordObject(this, "window");
            Undo.RecordObject(progressDB, "ProgressDB");
            if (selectedComponent != null)
            {
                Undo.RecordObject(selectedComponent, "PlayerProgression");
            }


            if (GUI.Button(new Rect(Math.Max(260, window.position.width - 120), 5, 100, 25), "Save"))
            {
                SetDirtyTDS();
            }

            if (!ProgressionStats_DB.UpdatedToPost_2018_3())
            {
                GUI.color = new Color(0, 1f, 1f, 1f);
                if (GUI.Button(new Rect(Math.Max(260, window.position.width - 230), 5, 100, 25), "Copy Old DB"))
                {
                    ProgressionStats_DB.CopyFromOldDB();
                }
                GUI.color = Color.white;
            }


            LevelProgressionStats stats = selectedComponent != null ? selectedComponent.stats : progressDB.stats;



            float startX = 5; float startY = 5; spaceX += 25;

            if (selectedComponent != null)
            {
                EditorGUI.HelpBox(new Rect(startX, startY, 250, 25), "Editing selected component", MessageType.Info);
            }
            else
            {
                EditorGUI.HelpBox(new Rect(startX, startY, 250, 25), "Editing Global Setting (DB)", MessageType.Info);
            }
            startY += 35;

            cont = new GUIContent("Level Cap:", "");
            EditorGUI.LabelField(new Rect(startX, startY, width, height), cont, headerStyle);
            stats.levelCap = EditorGUI.DelayedIntField(new Rect(startX + spaceX, startY, widthS, height), stats.levelCap);

            if (stats.levelCap != stats.expThresholdList.Count)
            {
                EditorGUI.HelpBox(new Rect(startX + spaceX + widthS + 20, startY, 250, 40), "Experience list doesn't match level cap.\nPlease Regenerate Experience List", MessageType.Warning);
                //EditorGUI.HelpBox(new Rect(startX, startY+spaceY, 250, 40), "Experience list doesn't match level cap.\nPlease Regenerate Experience List", MessageType.Warning);
                //startY+=2*spaceY;
            }

            startY = DrawPerLevelGain(startX, startY + spaceY + 15, stats);

            spaceX -= 25;

            DrawAddPerkGained(startX + spaceX + width - 80, startY + spaceY, stats);

            startY = DrawExpListGenerator(startX, startY + spaceY, stats);


            startY += 2 * spaceY;

            visibleRectList = new Rect(startX, startY, window.position.width - 10, window.position.height - startY - 5);
            contentRectList = new Rect(startX, startY, window.position.width - 25, contentLength);

            GUI.color = new Color(.8f, .8f, .8f, .8f);
            GUI.Box(visibleRectList, "");
            GUI.color = Color.white;

            scrollPosList = GUI.BeginScrollView(visibleRectList, scrollPosList, contentRectList);

            float cachedY = startY;

            startY        = DrawLevelList(startX, startY + 5, stats);
            contentLength = startY - cachedY;

            GUI.EndScrollView();

            if (selectedComponent != null)
            {
                PrefabUtility.RecordPrefabInstancePropertyModifications(selectedComponent);
            }

            if (GUI.changed)
            {
                if (selectedComponent != null)
                {
                    EditorUtility.SetDirty(selectedComponent);
                }
                SetDirtyTDS();
            }

            return(true);
        }
        Vector2 DrawSpawnerConfigurator(float startX, float startY, CollectibleSpawner spawner)
        {
            startY += 10;

            cont = new GUIContent("Spawn Area:", "The area which the unit should be spawn in\nIf unspecified, the unit will simply be spawned at the position of the spawner");
            EditorGUI.LabelField(new Rect(startX, startY, width, height), cont);
            spawner.spawnArea = (TDSArea)EditorGUI.ObjectField(new Rect(startX + spaceX, startY, width, height), spawner.spawnArea, typeof(TDSArea), true);

            startY += 10;

            if (GUI.Button(new Rect(startX + spaceX + width + 20, startY, 80, height), "Assign Self"))
            {
                TDSArea area = spawner.gameObject.GetComponent <TDSArea>();
                if (area == null)
                {
                    area = spawner.gameObject.AddComponent <TDSArea>();
                }
                spawner.spawnArea = area;
            }

            cont = new GUIContent("Spawn Upon Start:", "Check to have the spawner start spawning as soon as the game start");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);
            spawner.spawnUponStart = EditorGUI.Toggle(new Rect(startX + spaceX, startY, width, height), spawner.spawnUponStart);

            cont = new GUIContent("Start Delay:", "Delay (in second) before the spawning start");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);
            //if(spawner.spawnUponStart)
            spawner.startDelay = EditorGUI.DelayedFloatField(new Rect(startX + spaceX, startY, 40, height), spawner.startDelay);
            //else
            //	EditorGUI.LabelField(new Rect(startX+spaceX, startY, 40, height), "-");

            startY += 10;

            cont = new GUIContent("Spawn Cooldown:", "The cooldown between each spawn attempt");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);
            spawner.spawnCD = EditorGUI.DelayedFloatField(new Rect(startX + spaceX, startY, 40, height), spawner.spawnCD);

            cont = new GUIContent("Max Item Count:", "The maximum amount of active item in the game allowed by this spawner at any given item");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);
            spawner.maxItemCount = EditorGUI.DelayedIntField(new Rect(startX + spaceX, startY, 40, height), spawner.maxItemCount);

            cont = new GUIContent("Spawn Chance:", "The chance to successfully spawn an item during each cooldown cycle. Takes value from 0-1 with 0.3 being 30% to successfully spawn an item");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);
            spawner.spawnChance = EditorGUI.DelayedFloatField(new Rect(startX + spaceX, startY, 40, height), spawner.spawnChance);

            cont = new GUIContent("Fail Modifier:", "A modifier to the spawn chance should a spawn attempt fail (to prevent the attempt fail too many time in a row). ie if modifier is set as 0.1, each fail attempt will increase the spawn chance by 10%");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont);
            spawner.failModifier = EditorGUI.DelayedFloatField(new Rect(startX + spaceX, startY, 40, height), spawner.failModifier);

            startY += 10;

            cont = new GUIContent("Spawn Item:", "The collectible item available to this spawner");
            EditorGUI.LabelField(new Rect(startX, startY += spaceY, width, height), cont, headerStyle);

            int enabledCount = 0;

            for (int i = 0; i < collectibleDB.collectibleList.Count; i++)
            {
                Collectible colt = collectibleDB.collectibleList[i];


                CollectibleSpawnInfo spawnInfo = null;

                bool enabled = false;
                for (int n = 0; n < spawner.spawnItemList.Count; n++)
                {
                    enabled = spawner.spawnItemList[n].item == colt;
                    if (enabled)
                    {
                        spawnInfo = spawner.spawnItemList[n];
                        break;
                    }
                }
                bool enabledCached = enabled;

                float cachedX = startX;

                TDSEditorUtility.DrawSprite(new Rect(startX + 10, startY += spaceY, 30, 30), colt.icon, colt.desp);
                cont = new GUIContent(colt.collectibleName, colt.desp);
                EditorGUI.LabelField(new Rect(startX + 50, startY += 10, width, height), cont);
                enabled = EditorGUI.Toggle(new Rect(startX += (width), startY, 20, height), enabled);

                if (spawnInfo != null)
                {
                    cont = new GUIContent("Chance:", "Chance to spawn this item.\nThe way it works is a check against the individual item chance.\nA final candidate is then chosen over all item that pass the check.\nTakes value from 0-1 with 0.3 being 30% to pass the check");
                    EditorGUI.LabelField(new Rect(startX += 35, startY, width, height), cont);
                    spawnInfo.chance = EditorGUI.DelayedFloatField(new Rect(startX + 55, startY, 40, height), spawnInfo.chance);

                    cont = new GUIContent("Cooldown:", "The duration (in second) in which the item will be made unavailable after a successful spawn");
                    EditorGUI.LabelField(new Rect(startX += 120, startY, width, height), cont);
                    spawnInfo.cooldown = EditorGUI.DelayedFloatField(new Rect(startX + 65, startY, 40, height), spawnInfo.cooldown);
                }

                if (enabled != enabledCached)
                {
                    if (enabled)
                    {
                        spawnInfo      = new CollectibleSpawnInfo();
                        spawnInfo.item = colt;
                        spawner.spawnItemList.Insert(enabledCount, spawnInfo);
                    }
                    else
                    {
                        spawner.spawnItemList.Remove(spawnInfo);
                    }
                }

                if (enabled)
                {
                    enabledCount += 1;
                }

                startY += 4;

                startX = cachedX;
            }

            return(new Vector2(startX, startY + (1.5f * spaceY)));
        }
Esempio n. 23
0
 protected override void DrawArrayInternal(Rect rect, int array_size)
 {
     new_array_size = EditorGUI.DelayedIntField(GetElementRect(), array_size);
 }
Esempio n. 24
0
        public override object  OnGUI(Rect r, object instance)
        {
            r.height = Constants.SingleLineHeight;

            --EditorGUI.indentLevel;
            r.x += 3F;
            if (instance == null)
            {
                EditorGUI.BeginChangeCheck();
                EditorGUI.Foldout(r, false, this.label + " (Null)", false);
                if (EditorGUI.EndChangeCheck() == true)
                {
                    GUI.changed = false;
                }
            }
            else
            {
                EditorGUI.BeginChangeCheck();
                this.isExpanded = EditorGUI.Foldout(r, this.isExpanded, this.label, true);
                if (EditorGUI.EndChangeCheck() == true)
                {
                    NGEditorPrefs.SetBool(path, this.isExpanded);
                    GUI.changed = false;
                }
            }
            r.x -= 3F;
            ++EditorGUI.indentLevel;

            if (this.isExpanded == true)
            {
                r.y += r.height + 2F;
                ++EditorGUI.indentLevel;

                ICollectionModifier collection = NGTools.Utility.GetCollectionModifier(instance);

                if (collection != null)
                {
                    try
                    {
                        Type subType = collection.SubType;

                        EditorGUI.BeginChangeCheck();
                        int size = EditorGUI.DelayedIntField(r, "Size", collection.Size);
                        if (EditorGUI.EndChangeCheck() == true)
                        {
                            size = Mathf.Max(0, size);

                            if (collection.Size != size)
                            {
                                --EditorGUI.indentLevel;

                                if (instance is Array)
                                {
                                    Array newArray = Array.CreateInstance(subType, size);

                                    Array.Copy(instance as Array, newArray, Mathf.Min(collection.Size, size));

                                    if (collection.Size > 0)
                                    {
                                        object lastValue = collection.Get(collection.Size - 1);

                                        for (int i = collection.Size; i < size; i++)
                                        {
                                            newArray.SetValue(lastValue, i);
                                        }
                                    }

                                    instance = newArray;
                                }
                                else if (instance is IList)
                                {
                                    IList list = instance as IList;

                                    if (list.Count < size)
                                    {
                                        object lastValue = list.Count > 0 ? list[list.Count - 1] : (subType.IsValueType == true ? Activator.CreateInstance(subType) : null);

                                        while (list.Count < size)
                                        {
                                            list.Add(lastValue);
                                        }
                                    }
                                    else
                                    {
                                        while (list.Count > size)
                                        {
                                            list.RemoveAt(list.Count - 1);
                                        }
                                    }

                                    instance = list;
                                }
                                else
                                {
                                    throw new NotImplementedException("Collection of type \"" + instance.GetType() + "\" is not supported.");
                                }
                            }

                            return(instance);
                        }

                        while (this.drawers.Count < collection.Size)
                        {
                            this.drawers.Add(TypeDrawerManager.GetDrawer(this.path + '.' + this.drawers.Count.ToCachedString(), "Element " + this.drawers.Count.ToCachedString(), subType));
                        }

                        for (int i = 0; i < collection.Size; i++)
                        {
                            r.y += r.height + 2F;

                            object element = collection.Get(i);
                            r.height = this.drawers[i].GetHeight(element);

                            EditorGUI.BeginChangeCheck();
                            object value = this.drawers[i].OnGUI(r, element);
                            if (EditorGUI.EndChangeCheck() == true)
                            {
                                collection.Set(i, value);
                            }
                        }
                    }
                    finally
                    {
                        NGTools.Utility.ReturnCollectionModifier(collection);
                    }
                }

                --EditorGUI.indentLevel;
            }

            return(instance);
        }
Esempio n. 25
0
    public static void PropertyField(Rect position, SerializedProperty property, GUIContent label, bool includeChildren = false)
    {
        if (includeChildren || property.propertyType == SerializedPropertyType.Generic)
        {
            property.isExpanded = EditorGUILayout.Foldout(property.isExpanded, property.displayName);
            if (includeChildren && property.isExpanded)
            {
                foreach (SerializedProperty childProperty in property)
                {
                    PropertyField(position, childProperty, new GUIContent(property.displayName), false);
                }
            }

            return;
        }

        switch (property.propertyType)
        {
        case SerializedPropertyType.AnimationCurve:
            property.animationCurveValue = EditorGUI.CurveField(position, label, property.animationCurveValue);
            break;

        case SerializedPropertyType.ArraySize:
            property.intValue = EditorGUI.DelayedIntField(position, label, property.intValue);
            break;

        case SerializedPropertyType.Boolean:
            property.boolValue = EditorGUI.Toggle(position, label, property.boolValue);
            break;

        case SerializedPropertyType.Bounds:
            property.boundsValue = EditorGUI.BoundsField(position, label, property.boundsValue);
            break;

        case SerializedPropertyType.BoundsInt:
            property.boundsIntValue = EditorGUI.BoundsIntField(position, label, property.boundsIntValue);
            break;

        case SerializedPropertyType.Character:
            string newValue = EditorGUI.TextField(position, label, new string(new char[] { (char)property.intValue }));
            property.intValue = newValue.Length > 0 ? newValue[0] : '\0';
            break;

        case SerializedPropertyType.Color:
            property.colorValue = EditorGUI.ColorField(position, label, property.colorValue);
            break;

        case SerializedPropertyType.Enum:
            GUIContent[] displayNames = property.enumDisplayNames.Select(name => new GUIContent(name)).ToArray();
            property.enumValueIndex = EditorGUI.Popup(position, label, property.enumValueIndex, displayNames);
            break;

        case SerializedPropertyType.ExposedReference:
            property.exposedReferenceValue = EditorGUI.ObjectField(position, label, property.objectReferenceValue, ReflectionExtensions.GetType(property), true);
            break;

        case SerializedPropertyType.Float:
            property.floatValue = EditorGUI.FloatField(position, label, property.floatValue);
            break;

        case SerializedPropertyType.Integer:
            property.intValue = EditorGUI.IntField(position, label, property.intValue);
            break;

        case SerializedPropertyType.LayerMask:
            MethodInfo method = typeof(EditorGUI).GetMethods(BindingFlags.NonPublic | BindingFlags.Static).First(t => t.Name == "LayerMaskField");
            method.Invoke(null, new object[] { position, property, label });
            break;

        case SerializedPropertyType.ObjectReference:
            property.objectReferenceValue = EditorGUI.ObjectField(position, label, property.objectReferenceValue, ReflectionExtensions.GetType(property), true);
            break;

        case SerializedPropertyType.Quaternion:
            Quaternion quaternion       = property.quaternionValue;
            Vector4    quaternionValues = new Vector4(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
            quaternionValues         = EditorGUI.Vector4Field(position, label, quaternionValues);
            property.quaternionValue = new Quaternion(quaternionValues.x, quaternionValues.y, quaternionValues.z, quaternionValues.w);
            break;

        case SerializedPropertyType.Rect:
            property.rectValue = EditorGUI.RectField(position, label, property.rectValue);
            break;

        case SerializedPropertyType.RectInt:
            property.rectIntValue = EditorGUI.RectIntField(position, label, property.rectIntValue);
            break;

        case SerializedPropertyType.String:
            property.stringValue = EditorGUI.TextField(position, label, property.stringValue);
            break;

        case SerializedPropertyType.Vector2:
            property.vector2Value = EditorGUI.Vector2Field(position, label, property.vector2Value);
            break;

        case SerializedPropertyType.Vector2Int:
            property.vector2IntValue = EditorGUI.Vector2IntField(position, label, property.vector2IntValue);
            break;

        case SerializedPropertyType.Vector3:
            property.vector3Value = EditorGUI.Vector3Field(position, label, property.vector3Value);
            break;

        case SerializedPropertyType.Vector3Int:
            property.vector3IntValue = EditorGUI.Vector3IntField(position, label, property.vector3IntValue);
            break;

        case SerializedPropertyType.Vector4:
            property.vector4Value = EditorGUI.Vector4Field(position, label, property.vector4Value);
            break;

        /*
         * case SerializedPropertyType.Gradient:
         * var method = typeof(EditorGUI).GetMethods(BindingFlags.NonPublic | BindingFlags.Static).First(t => t.Name == "GradientField");
         * var change = m.Invoke(null, new object[] { rect, gradient });
         * method = typeof(EditorGUI).GetMethods(BindingFlags.NonPublic | BindingFlags.Static).First(t => t.Name == "DefaultPropertyField");
         * method.Invoke(null, new object[] { position, property, label });
         * break;
         */
        default:
            Debug.LogError("SerializedPropertyType: " + property.propertyType + " not handled");
            break;
        }
    }
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            SerializedProperty prop_Unicode    = property.FindPropertyRelative("m_Unicode");
            SerializedProperty prop_GlyphIndex = property.FindPropertyRelative("m_GlyphIndex");
            SerializedProperty prop_Scale      = property.FindPropertyRelative("m_Scale");


            GUIStyle style = new GUIStyle(EditorStyles.label);

            style.richText = true;

            EditorGUIUtility.labelWidth = 40f;
            EditorGUIUtility.fieldWidth = 50;

            Rect rect = new Rect(position.x + 50, position.y, position.width, 49);

            // Display non-editable fields
            if (GUI.enabled == false)
            {
                int unicode = prop_Unicode.intValue;
                EditorGUI.LabelField(new Rect(rect.x, rect.y, 120f, 18), new GUIContent("Unicode: <color=#FFFF80>0x" + unicode.ToString("X") + "</color>"), style);
                EditorGUI.LabelField(new Rect(rect.x + 115, rect.y, 120f, 18), unicode <= 0xFFFF ? new GUIContent("UTF16: <color=#FFFF80>\\u" + unicode.ToString("X4") + "</color>") : new GUIContent("UTF32: <color=#FFFF80>\\U" + unicode.ToString("X8") + "</color>"), style);
                EditorGUI.LabelField(new Rect(rect.x, rect.y + 18, 120, 18), new GUIContent("Glyph ID: <color=#FFFF80>" + prop_GlyphIndex.intValue + "</color>"), style);
                EditorGUI.LabelField(new Rect(rect.x, rect.y + 36, 80, 18), new GUIContent("Scale: <color=#FFFF80>" + prop_Scale.floatValue + "</color>"), style);

                // Draw Glyph (if exists)
                DrawGlyph(position, property);
            }
            else // Display editable fields
            {
                EditorGUIUtility.labelWidth = 55f;
                GUI.SetNextControlName("Unicode Input");
                EditorGUI.BeginChangeCheck();
                string unicode = EditorGUI.TextField(new Rect(rect.x, rect.y, 120, 18), "Unicode:", prop_Unicode.intValue.ToString("X"));

                if (GUI.GetNameOfFocusedControl() == "Unicode Input")
                {
                    //Filter out unwanted characters.
                    char chr = Event.current.character;
                    if ((chr < '0' || chr > '9') && (chr < 'a' || chr > 'f') && (chr < 'A' || chr > 'F'))
                    {
                        Event.current.character = '\0';
                    }
                }

                if (EditorGUI.EndChangeCheck())
                {
                    // Update Unicode value
                    prop_Unicode.intValue = TextUtilities.StringHexToInt(unicode);
                }

                // Cache current glyph index in case it needs to be restored if the new glyph index is invalid.
                int currentGlyphIndex = prop_GlyphIndex.intValue;

                EditorGUIUtility.labelWidth = 59f;
                EditorGUI.BeginChangeCheck();
                EditorGUI.DelayedIntField(new Rect(rect.x, rect.y + 18, 100, 18), prop_GlyphIndex, new GUIContent("Glyph ID:"));
                if (EditorGUI.EndChangeCheck())
                {
                    // Get a reference to the font asset
                    FontAsset fontAsset = property.serializedObject.targetObject as FontAsset;

                    // Make sure new glyph index is valid.
                    int elementIndex = fontAsset.glyphTable.FindIndex(item => item.index == prop_GlyphIndex.intValue);

                    if (elementIndex == -1)
                    {
                        prop_GlyphIndex.intValue = currentGlyphIndex;
                    }
                    else
                    {
                        fontAsset.m_IsFontAssetLookupTablesDirty = true;
                    }
                }

                int glyphIndex = prop_GlyphIndex.intValue;

                // Reset glyph selection if new character has been selected.
                if (GUI.enabled && m_GlyphSelectedForEditing != glyphIndex)
                {
                    m_GlyphSelectedForEditing = -1;
                }

                // Display button to edit the glyph data.
                if (GUI.Button(new Rect(rect.x + 120, rect.y + 18, 75, 18), new GUIContent("Edit Glyph")))
                {
                    if (m_GlyphSelectedForEditing == -1)
                    {
                        m_GlyphSelectedForEditing = glyphIndex;
                    }
                    else
                    {
                        m_GlyphSelectedForEditing = -1;
                    }

                    // Button clicks should not result in potential change.
                    GUI.changed = false;
                }

                // Show the glyph property drawer if selected
                if (glyphIndex == m_GlyphSelectedForEditing && GUI.enabled)
                {
                    // Get a reference to the font asset
                    FontAsset fontAsset = property.serializedObject.targetObject as FontAsset;

                    if (fontAsset != null)
                    {
                        // Get the index of the glyph in the font asset glyph table.
                        int elementIndex = fontAsset.glyphTable.FindIndex(item => item.index == glyphIndex);

                        if (elementIndex != -1)
                        {
                            SerializedProperty prop_GlyphTable = property.serializedObject.FindProperty("m_GlyphTable");
                            SerializedProperty prop_Glyph      = prop_GlyphTable.GetArrayElementAtIndex(elementIndex);

                            SerializedProperty prop_GlyphMetrics = prop_Glyph.FindPropertyRelative("m_Metrics");
                            SerializedProperty prop_GlyphRect    = prop_Glyph.FindPropertyRelative("m_GlyphRect");

                            Rect newRect = EditorGUILayout.GetControlRect(false, 115);
                            EditorGUI.DrawRect(new Rect(newRect.x + 52, newRect.y - 20, newRect.width - 52, newRect.height - 5), new Color(0.1f, 0.1f, 0.1f, 0.45f));
                            EditorGUI.DrawRect(new Rect(newRect.x + 53, newRect.y - 19, newRect.width - 54, newRect.height - 7), new Color(0.3f, 0.3f, 0.3f, 0.8f));

                            // Display GlyphRect
                            newRect.x     += 55;
                            newRect.y     -= 18;
                            newRect.width += 5;
                            EditorGUI.PropertyField(newRect, prop_GlyphRect);

                            // Display GlyphMetrics
                            newRect.y += 45;
                            EditorGUI.PropertyField(newRect, prop_GlyphMetrics);

                            rect.y += 120;
                        }
                    }
                }

                EditorGUIUtility.labelWidth = 39f;
                EditorGUI.PropertyField(new Rect(rect.x, rect.y + 36, 80, 18), prop_Scale, new GUIContent("Scale:"));

                // Draw Glyph (if exists)
                DrawGlyph(position, property);
            }
        }
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        const float textWidthPercent  = 0.3f;
        const float textColorPercent  = 0.6f;
        const float textRemovePercent = 0.1f;

        Undo.RecordObject(property.serializedObject.targetObject, "name");

        // Using BeginProperty / EndProperty on the parent property means that
        // prefab override logic works on the entire property.
        EditorGUI.BeginProperty(position, label, property);

        // Draw label
        position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), new GUIContent("Color lookup table"));

        // Don't make child fields be indented
        var indent = EditorGUI.indentLevel;

        EditorGUI.indentLevel = 0;

        HeightmapColorLookupTable propertyLut = (HeightmapColorLookupTable)fieldInfo.GetValue(property.serializedObject.targetObject);

        Rect rectNextKeyAdd   = new Rect(position.x + position.width * textWidthPercent, position.y + (propertyLut.Keys.Count) * lineHeight, position.width * (1.0f - textWidthPercent), lineHeight);
        Rect rectNextKeyInput = new Rect(position.x, position.y + (propertyLut.Keys.Count) * lineHeight, position.width * textWidthPercent, lineHeight);

        if (propertyLut.Keys.Count == 0)
        {
            Rect rectObjectInput = new Rect(position.x, position.y + 1 * lineHeight, position.width, lineHeight);

            TextAsset textAsset = (TextAsset)EditorGUI.ObjectField(rectObjectInput, "Color lookup table json", null, typeof(TextAsset), false);
            if (textAsset != null)
            {
                propertyLut.Overwrite(textAsset.text);
            }
        }

        for (int i = 0; i < propertyLut.Keys.Count; i++)
        {
            Rect rectText      = new Rect(position.x, position.y + i * lineHeight, position.width * textWidthPercent, lineHeight);
            Rect rectColor     = new Rect(position.x + position.width * textWidthPercent, position.y + i * lineHeight, position.width * textColorPercent, lineHeight);
            Rect rectRemoveKey = new Rect(position.x + position.width * (textWidthPercent + textColorPercent), position.y + i * lineHeight, position.width * textRemovePercent, lineHeight);

            EditorGUI.LabelField(rectText, propertyLut.Keys[i].ToString());

            Color val = EditorGUI.ColorField(rectColor, propertyLut[propertyLut.Keys[i]]);
            if (val != propertyLut[propertyLut.Keys[i]])
            {
                propertyLut[propertyLut.Keys[i]] = val;
            }

            if (!EditorGUI.Toggle(rectRemoveKey, true))
            {
                propertyLut.Remove(propertyLut.Keys[i]);
            }
        }

        EditorGUI.BeginChangeCheck();
        nextInd = EditorGUI.DelayedIntField(rectNextKeyInput, nextInd);
        if (EditorGUI.EndChangeCheck())
        {
            propertyLut[nextInd] = Color.white;
        }

        EditorGUI.indentLevel = indent;

        EditorGUI.EndProperty();

        property.serializedObject.ApplyModifiedProperties();
    }
Esempio n. 28
0
        void DrawWheel(ref Vector4 value, bool overrideState)
        {
            var   wheelRect = GUILayoutUtility.GetAspectRect(1f);
            float size      = wheelRect.width;
            float hsize     = size / 2f;
            float radius    = 0.38f * size;

            Vector3 hsv;

            Color.RGBToHSV(value, out hsv.x, out hsv.y, out hsv.z);
            float offset = value.w;

            // Thumb
            var   thumbPos = Vector2.zero;
            float theta    = hsv.x * (Mathf.PI * 2f);

            thumbPos.x = Mathf.Cos(theta + (Mathf.PI / 2f));
            thumbPos.y = Mathf.Sin(theta - (Mathf.PI / 2f));
            thumbPos  *= hsv.y * radius;

            // Draw the wheel
            if (Event.current.type == EventType.Repaint)
            {
                // Style init
                if (s_WheelThumb == null)
                {
                    s_WheelThumb     = new GUIStyle("ColorPicker2DThumb");
                    s_WheelThumbSize = new Vector2(
                        !Mathf.Approximately(s_WheelThumb.fixedWidth, 0f) ? s_WheelThumb.fixedWidth : s_WheelThumb.padding.horizontal,
                        !Mathf.Approximately(s_WheelThumb.fixedHeight, 0f) ? s_WheelThumb.fixedHeight : s_WheelThumb.padding.vertical
                        );
                }

                // Retina support
                float scale = EditorGUIUtility.pixelsPerPoint;

                // Wheel texture
                var oldRT = RenderTexture.active;
                var rt    = RenderTexture.GetTemporary((int)(size * scale), (int)(size * scale), 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB);
                s_Material.SetFloat("_Offset", offset);
                s_Material.SetFloat("_DisabledState", overrideState && GUI.enabled ? 1f : 0.5f);
                s_Material.SetVector("_Resolution", new Vector2(size * scale, size * scale / 2f));
                Graphics.Blit(null, rt, s_Material, EditorGUIUtility.isProSkin ? 0 : 1);
                RenderTexture.active = oldRT;

                GUI.DrawTexture(wheelRect, rt);
                RenderTexture.ReleaseTemporary(rt);

                var thumbSize  = s_WheelThumbSize;
                var thumbSizeH = thumbSize / 2f;
                s_WheelThumb.Draw(new Rect(wheelRect.x + hsize + thumbPos.x - thumbSizeH.x, wheelRect.y + hsize + thumbPos.y - thumbSizeH.y, thumbSize.x, thumbSize.y), false, false, false, false);
            }

            // Input
            var bounds = wheelRect;

            bounds.x    += hsize - radius;
            bounds.y    += hsize - radius;
            bounds.width = bounds.height = radius * 2f;
            hsv          = GetInput(bounds, hsv, thumbPos, radius);


            Vector3Int displayHSV         = new Vector3Int(Mathf.RoundToInt(hsv.x * 360), Mathf.RoundToInt(hsv.y * 100), 100);
            bool       displayInputFields = EditorGUIUtility.currentViewWidth > 600;

            if (displayInputFields)
            {
                var valuesRect = GUILayoutUtility.GetRect(1f, 17f);
                valuesRect.width /= 5f;
                float textOff = valuesRect.width * 0.2f;
                EditorGUI.LabelField(valuesRect, "Y");
                valuesRect.x += textOff;
                offset        = EditorGUI.DelayedFloatField(valuesRect, offset);
                offset        = Mathf.Clamp(offset, -1.0f, 1.0f);
                valuesRect.x += valuesRect.width + valuesRect.width * 0.05f;
                EditorGUI.LabelField(valuesRect, "H");
                valuesRect.x += textOff;
                displayHSV.x  = EditorGUI.DelayedIntField(valuesRect, displayHSV.x);
                hsv.x         = displayHSV.x / 360.0f;
                valuesRect.x += valuesRect.width + valuesRect.width * 0.05f;
                EditorGUI.LabelField(valuesRect, "S");
                valuesRect.x += textOff;
                displayHSV.y  = EditorGUI.DelayedIntField(valuesRect, displayHSV.y);
                displayHSV.y  = Mathf.Clamp(displayHSV.y, 0, 100);
                hsv.y         = displayHSV.y / 100.0f;
                valuesRect.x += valuesRect.width + valuesRect.width * 0.05f;
                EditorGUI.LabelField(valuesRect, "V");
                valuesRect.x += textOff;
                GUI.enabled   = false;
                EditorGUI.IntField(valuesRect, 100);
                GUI.enabled = true;
            }


            value   = Color.HSVToRGB(hsv.x, hsv.y, 1f);
            value.w = offset;

            // Offset
            var   sliderRect = GUILayoutUtility.GetRect(1f, 17f);
            float padding    = sliderRect.width * 0.05f; // 5% padding

            sliderRect.xMin += padding;
            sliderRect.xMax -= padding;
            value.w          = GUI.HorizontalSlider(sliderRect, value.w, -1f, 1f);

            if (m_ComputeFunc == null)
            {
                return;
            }

            // Values
            var displayValue = m_ComputeFunc(value);

            using (new EditorGUI.DisabledGroupScope(true))
            {
                var valuesRect = GUILayoutUtility.GetRect(1f, 17f);
                valuesRect.width /= (displayInputFields ? 4f : 3.0f);
                if (displayInputFields)
                {
                    GUI.Label(valuesRect, "RGB Value:", EditorStyles.centeredGreyMiniLabel);
                    valuesRect.x += valuesRect.width;
                }
                GUI.Label(valuesRect, displayValue.x.ToString("F2"), EditorStyles.centeredGreyMiniLabel);
                valuesRect.x += valuesRect.width;
                GUI.Label(valuesRect, displayValue.y.ToString("F2"), EditorStyles.centeredGreyMiniLabel);
                valuesRect.x += valuesRect.width;
                GUI.Label(valuesRect, displayValue.z.ToString("F2"), EditorStyles.centeredGreyMiniLabel);
                valuesRect.x += valuesRect.width;
            }
        }
        void OnEnable()
        {
            m_component = (PowerSpriteImport)target;
            m_items     = m_component.m_animations;

            if (Directory.Exists(m_component.m_sourceDirectory) == false)
            {
                m_component.m_sourceDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);
            }

            RecalcLengths();

            m_list = new ReorderableList(serializedObject, serializedObject.FindProperty(LIST_PROPERTY_NAME), true, true, true, true);
            m_list.drawHeaderCallback = (Rect rect) => {
                EditorGUI.LabelField(new Rect(rect)
                {
                    width = rect.width
                }, "Animation Name");
                EditorGUI.LabelField(new Rect(rect)
                {
                    x = rect.width - 47, width = 100
                }, "First Frame");
            };

            m_list.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) =>
            {
                SerializedProperty listItem = m_list.serializedProperty.GetArrayElementAtIndex(index);
                rect.y += 2;
                EditorGUI.BeginChangeCheck();
                EditorGUI.PropertyField(new Rect(rect.x, rect.y, rect.width - 45, EditorGUIUtility.singleLineHeight),
                                        listItem.FindPropertyRelative("m_name"), GUIContent.none);
                if (EditorGUI.EndChangeCheck())
                {
                    m_list.index = index;
                }
                //EditorGUI.LabelField(new Rect(rect.x + rect.width-90, rect.y, 90, EditorGUIUtility.singleLineHeight), "1st frame:");
                EditorGUI.BeginChangeCheck();
                m_items[index].m_firstFrame = EditorGUI.DelayedIntField(new Rect(rect.x + rect.width - 40, rect.y, 40, EditorGUIUtility.singleLineHeight), m_items[index].m_firstFrame);
                if (EditorGUI.EndChangeCheck())
                {
                    // Recalc previous length since it will have changed
                    if (index > 0)
                    {
                        m_items[index - 1].m_length = Mathf.Max(1, m_items[index].m_firstFrame - m_items[index - 1].m_firstFrame);
                    }
                    // Recalc first frames
                    RecalcFirstFrames();
                }
            };
            m_list.onAddCallback += (list) =>
            {
                if (m_list.index < 0 || m_list.index >= m_list.count - 1)
                {
                    m_items.Add(new PowerSpriteImport.AnimImportData());
                    m_list.index = m_list.index + 1;
                }
                else
                {
                    m_items.Insert(m_list.index + 1, new PowerSpriteImport.AnimImportData());
                    m_list.index = m_list.index + 1;
                }
                RecalcFirstFrames();
            };
            m_list.onRemoveCallback += (list) =>
            {
                int index = m_list.index;
                m_items.RemoveAt(m_list.index);
                RecalcFirstFrames();
                index--;
                if (index >= 0)
                {
                    m_list.index = index;
                }
            };
            m_list.onReorderCallback += (list) =>
            {
                RecalcFirstFrames();
            };
        }
Esempio n. 30
0
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        // Get the property values
        SerializedProperty minProperty = property.FindPropertyRelative(MIN_VALUE_NAME);
        SerializedProperty maxProperty = property.FindPropertyRelative(MAX_VALUE_NAME);

        // Default min/max range values
        int   minInt   = 0;
        int   maxInt   = 0;
        float minFloat = 0;
        float maxFloat = 0;

        // Set the min/max range value if the range type is float
        if (property.type == VALUE_RANGE_TYPE_NAME)
        {
            minFloat = minProperty.floatValue;
            maxFloat = maxProperty.floatValue;
        }
        // Set the min/max range value if the range type is int
        // Set the float as well, because sliders only deal with floats
        else
        {
            minInt = minProperty.intValue;
            maxInt = maxProperty.intValue;

            minFloat = minInt;
            maxFloat = maxInt;
        }

        // Draw the name of the property
        EditorGUI.LabelField(position, label);

        // Calculate the rect that the properties have
        Rect propertyRect = position;

        propertyRect.x     += EditorGUIUtility.labelWidth;
        propertyRect.width -= EditorGUIUtility.labelWidth;

        // Calculate the rect that the min property has
        Rect minPropertyRect = propertyRect;

        minPropertyRect.width *= 0.5f;
        minPropertyRect.width -= FIELD_SPACING;

        // Calculate the rect that the max property has
        Rect maxPropertyRect = minPropertyRect;

        maxPropertyRect.x += maxPropertyRect.width + FIELD_SPACING * 2;

        // Calculate the rect for the min property label
        Rect minLabelRect = minPropertyRect;

        minLabelRect.width = FIELD_WIDTH;

        // Calculate the rect for the max property label
        Rect maxLabelRect = maxPropertyRect;

        maxLabelRect.width = FIELD_WIDTH;

        // Calculate the rect for the min property
        Rect minFieldRect = minPropertyRect;

        minFieldRect.x     += minLabelRect.width;
        minFieldRect.width -= minLabelRect.width;

        // Calculate the rect for the max property
        Rect maxFieldRect = maxPropertyRect;

        maxFieldRect.x     += maxLabelRect.width;
        maxFieldRect.width -= maxLabelRect.width;

        // Draw the min label and min property
        EditorGUI.PrefixLabel(minLabelRect, new GUIContent("Min"));
        if (property.type == VALUE_RANGE_TYPE_NAME)
        {
            minFloat = EditorGUI.DelayedFloatField(minFieldRect, minProperty.floatValue);
        }
        else
        {
            minInt = EditorGUI.DelayedIntField(minFieldRect, minProperty.intValue);
        }

        // Draw the max lavel and max property
        EditorGUI.PrefixLabel(maxLabelRect, new GUIContent("Max"));
        if (property.type == VALUE_RANGE_TYPE_NAME)
        {
            maxFloat = EditorGUI.DelayedFloatField(maxFieldRect, maxProperty.floatValue);
        }
        else
        {
            maxInt = EditorGUI.DelayedIntField(maxFieldRect, maxProperty.intValue);
        }

        // Set the min/max values of the range if after the inspector updates
        minProperty.floatValue = Mathf.Min(minFloat, maxFloat);
        maxProperty.floatValue = Mathf.Max(minFloat, maxFloat);
        minProperty.intValue   = Mathf.Min(minInt, maxInt);
        maxProperty.intValue   = Mathf.Max(minInt, maxInt);
    }