【问题标题】:Custom value slider unity自定义值滑块统一
【发布时间】:2021-11-16 10:55:15
【问题描述】:

我想返回显示值 (a,b,c,d) 而不是数字 (0.01-0.019 等) 帮助会很好,很多人会很高兴。 这段代码看起来像百分比显示,但我不想要百分比我想要一个文本

Mathf.RoundToInt(value * 100) + "%"

【问题讨论】:

  • 对你想要做的事情有点困惑,你的意思是数字到文本中的“50%”到“50%”吗?
  • 不,我只需要拖动滑块时的文本
  • @VaporMarin 我添加了两个解决方案。一个专门用于字母数字输出,另一个用于映射到数字的更通用的字符串值。
  • 创建一个文本数组 .. 使用只有完整整数步长的滑块 -> 每一步都是数组的索引 .. 完成

标签: unity3d slider letter


【解决方案1】:

与其制作全新的自定义滑块,不如利用 Unity 已经提供的功能,然后将输出映射到您想要的任何格式。滑块可以设置为具有固定数量的输出,也可以设置为仅固定为整数。

如果您在编辑器中查看滑块组件,则应设置字段Min ValueMax ValueWhole 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];
}

下面是它的动图:

如果您有任何问题,请告诉我。我不确定您是否也希望在滑块上直观地显示这些标记,但这也可以使用标准化位置和水平布局组来完成。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-05
    • 2018-01-28
    • 1970-01-01
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-09
    相关资源
    最近更新 更多