栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 游戏开发 > 其他

Unity最大值和最小值约束调整

其他 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Unity最大值和最小值约束调整

问题

现在我们有一个变量,我们希望可以在编辑器面板上自由调节它的最小值和最大值


通过简单的代码编写我们很容易实现了这个功能,但是我们察觉到如果在调整时最小值不小心大于最大值,那么结果将达不到我们的预期,有什么好办法来实现这个功能呢?

解决方法

用该部分代码代替原有的四个变量

可以看到下面两个拖动条就是我们新增的,通过拖动滑动条来赋值最大值和最小值即可解决问题,也就不会出现不小心最小值大于最大值的隐患了

要实现这个效果我们需要3个脚本

using System;

[Serializable]
public struct RangedFloat
{
    public float minValue;
    public float maxValue;
}

using System;

public class MinMaxRangeAttribute : Attribute
{
    public float Min
    {
        get;
        private set;
    }

    public float Max
    {
        get;
        private set;
    }

    public MinMaxRangeAttribute(float min,float max)
    {
        Min = min;
        Max = max;
    }
}

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

[CustomPropertyDrawer(typeof(RangedFloat),true)]
public class RangedFloatDrawer : PropertyDrawer
{
    //base.OnGUI(position, property, label);
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        label = EditorGUI.BeginProperty(position, label, property);
        position = EditorGUI.PrefixLabel(position,label);

        SerializedProperty minProp = property.FindPropertyRelative("minValue");
        SerializedProperty maxProp = property.FindPropertyRelative("maxValue");

        float minValue = minProp.floatValue;
        float maxValue = maxProp.floatValue;

        float rangeMin = 0;
        float rangeMax = 1;

        var ranges = (MinMaxRangeAttribute[])fieldInfo.GetCustomAttributes(typeof(MinMaxRangeAttribute),true);
        if (ranges.Length > 0)
        {
            rangeMin = ranges[0].Min;
            rangeMax = ranges[0].Max;
        }

        const float rangeBoundsLabelWidth = 40f;
        var rangeBoundsLabel1Rect = new Rect(position);
        rangeBoundsLabel1Rect.width = rangeBoundsLabelWidth;
        GUI.Label(rangeBoundsLabel1Rect,new GUIContent(minValue.ToString("F2")));
        position.xMin += rangeBoundsLabelWidth;

        var rangeBoundsLabel2Rect = new Rect(position);
        rangeBoundsLabel2Rect.xMin = rangeBoundsLabel2Rect.xMax - rangeBoundsLabelWidth;
        GUI.Label(rangeBoundsLabel2Rect,new GUIContent(maxValue.ToString("F2")));
        position.xMax -= rangeBoundsLabelWidth;

        EditorGUI.BeginChangeCheck();
        EditorGUI.MinMaxSlider(position,ref minValue,ref maxValue,rangeMin,rangeMax);
        if (EditorGUI.EndChangeCheck())
        {
            minProp.floatValue = minValue;
            maxProp.floatValue = maxValue;
        }
        EditorGUI.EndProperty();
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/901267.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号