How can I link a slider to an InputField?

I’m trying to make it so whenever someone moves the slider, the value in the InputField changes and viceversa (whatever value you write in the InputField changes the value of the slider). So far I’ve managed to convert the float value from the slider into a string and show it in the InputField, but that doesn’t mean that both share the same value right?

If someone finds a way to link both values I would very much appreciate it. Thanks!

Here is my script right now:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Question1 : MonoBehaviour
{
    public GameObject panel;

    public Slider yearSliderQ1;
    public Slider yearSliderQ2;

    public TMPro.TMP_InputField inputField1;
    public TMPro.TMP_InputField inputField2;

    // Initialize Q1
    void Start()
    {
        panel.SetActive(true);
    }

    void Update()
    {
        float yearAge = yearSliderQ1.value;
        float yearBorn = yearSliderQ2.value;

        inputField1.text = yearAge.ToString();
        inputField2.text = yearBorn.ToString();
    }

Hi!

You can use the on value changed event of the field/slider to update the other. This way you don’t have to store each of their values and check every frame to figure out if they changed:

void Start()
{
    mySlider.onValueChanged.AddListener(OnSliderChanged);
    myField.onValueChanged.AddListener(OnFieldChanged);
}

private void OnSliderChanged(float number)
{
    if (myField.text != number.ToString())
    {
        myField.text = number.ToString();
    }
}

private void OnFieldChanged(string text)
{
    if (mySlider.value.ToString() != text)
    {
        if (float.TryParse(text, out float number))
        {
            mySlider.value = number;
        }
    }
}

We do first have to check if it even changed before converting and setting the value to the slider so that we avoid an infinite loop of each change triggering another. But apart from that the only intersting thing is that you convert a written number to an actual one with float.Parse().

Hope this helps! :slight_smile: