与其制作全新的自定义滑块,不如利用 Unity 已经提供的功能,然后将输出映射到您想要的任何格式。滑块可以设置为具有固定数量的输出,也可以设置为仅固定为整数。
如果您在编辑器中查看滑块组件,则应设置字段Min Value、Max Value 和Whole Numbers。最重要的是将 Whole Numbers 设置为 true 并将 Max Value 设置为可能的最高值 - 新映射集的 1。
接下来,当滑块的值发生变化时,您需要为脚本设置回调委托以检索值。
您可以使用编辑器中的UnityAction UI 在编辑器中添加回调,也可以通过访问onValueChange 侦听器并添加新侦听器以编程方式添加回调。例如,我将在代码中做所有事情以消除任何混乱。
剩下的就是将我们的滑块输出的检索值映射到一些所需的输出。由于您想要的输出似乎只是字母数字值,您实际上可以通过知道取一个整数值并将字符“a”添加到它会导致相应的字母数字值(其中 0 映射到 a 和25 到 z)。
[SerializeField] private Slider slider = null;
private void Start()
{
slider.onValueChanged.AddListener(delegate { SliderValueChangedCallback(); });
}
/// <summary>
/// Called when our slider value changes
/// </summary>
private void SliderValueChangedCallback()
{
// grab out numeric value of the slider - cast to int as the value should be a whole number
int numericSliderValue = (int)slider.value;
// now, plot our value to an alphanumeric one
char alphaNumericValue = (char)(numericSliderValue + 'a');
Debug.Log(alphaNumericValue);
}
现在,此解决方案仅在您希望输出值是字母数字值时才有效。如果您想要更模块化的解决方案,这里有一个:
[SerializeField] private Slider slider = null;
[SerializeField] private Text currentValue = null;
[SerializeField] private List<string> yourValueList = new List<string> { "First Message", "Second Message", "Third Value", "4 for some reason", "the letter 6" };
private void Start()
{
slider.onValueChanged.AddListener(delegate { SliderValueChangedCallback(); });
// assuring that our slider is setup properly to map values
slider.minValue = 0;
slider.maxValue = yourValueList.Count - 1;
slider.wholeNumbers = true;
}
/// <summary>
/// Called when our slider value changes
/// </summary>
private void SliderValueChangedCallback()
{
// grab out numeric value of the slider - cast to int as the value should be a whole number
int numericSliderValue = (int)slider.value;
// debugging - do whatever you want with this value
currentValue.text = yourValueList[numericSliderValue];
}
下面是它的动图:
如果您有任何问题,请告诉我。我不确定您是否也希望在滑块上直观地显示这些标记,但这也可以使用标准化位置和水平布局组来完成。