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();
    }
}

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值