问题
现在我们有一个变量,我们希望可以在编辑器面板上自由调节它的最小值和最大值
通过简单的代码编写我们很容易实现了这个功能,但是我们察觉到如果在调整时最小值不小心大于最大值,那么结果将达不到我们的预期,有什么好办法来实现这个功能呢?
解决方法
用该部分代码代替原有的四个变量
可以看到下面两个拖动条就是我们新增的,通过拖动滑动条来赋值最大值和最小值即可解决问题,也就不会出现不小心最小值大于最大值的隐患了
要实现这个效果我们需要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();
}
}