Search code examples
unity-game-engineuser-interfaceunity3d-2dtools

can the ui.inputfield have the data from both text box and input displayed overlaying each other?


I have a Unity Droid app with an ui.inputfield. I am giving the user the ability to enter numbers or move a slider. In either case I need to have the slider data appear in the inputfield or update the slider position with the number typed into the inputfield. I can get the data from both the inputfield or the slider but I need to have the data displayed. My main concern is can I have the data from both inputs displayed at the exact same location as the inputfield, like on top? I can not find any examples of the data display on top of the input field. Is this the correct way to think about this? Thank you in advance.


Solution

  • There are callbacks whenever the user changes a UI.Slider or finishes entering a value in a UI.InputField:

    So yes you could link them to each other like e.g.

    public class Example : MonoBehaviour
    {
        public InputField inputField;
        public Slider slider;
    
        private void Awake()
        {
            inputField.onEndEdit.AddListener(OnInputFieldChanged);
            slider.onValueChanged .AddListener( OnSliderChanged);
    
            OnSliderChanged(slider.value);
        }
    
        private void OnInputFieldChanged(string newText)
        {
            if (float.TryParse(newText, out var value))
            {
                value = Mathf.Clamp(value, slider.minValue, slider.maxValue);
    
                inputField.text = value.ToString("F");
                slider.value = value;
            }
            else
            {
                Debug.LogWarning("Input Format Error!", this);
                slider.value = Mathf.Clamp(0, slider.minValue, slider.maxValue);
                inputField.text = slider.value.ToString("F");
            }
        }
    
        private void OnSliderChanged(float newValue)
        {
            inputField.text = newValue.ToString("F");
        }
    }
    

    enter image description here