InputField onValueChanged

I have a problem with calling onValueChanged on an InputField. It seems that currentText is updated before entering if case. Maybe I’m not seeing something. Any idea?


  • Example

  • First Step:

  • Inputfield: abcd

  • currentText: abcd

  • Second Step:

  • Remove “d”

  • currentText: abc

  • oldText: abc

       // Script 1
     public override void SetText(InputField _currentText)
     {
    
         if (currentText != null /*&& currentText != oldText*/)
         {
             Debug.Log("Current text: " + currentText.text);
             oldText = currentText;
             Debug.Log("Old text: " + oldText.text);
         }
    
         currentText = _currentText;
    
         Debug.Log("Current text: " + currentText.text);
     }
    
    // Script 2
     private void Start()
     {
         editedText = new TextReceiver();
         textField.onValueChanged.AddListener(delegate { editedText.SetText(textField); });
     }
    

Simply because currentText,oldText, _currentText and textField are referencing the same inputfield. InputField is a class (reference type), so when you assign oldText = currentText, you are just telling oldText will reference the same InputField as currentText. and the following line textField.onValueChanged.AddListener(delegate { editedText.SetText(textField); }); won(t create a “new” inputfield each time the function is called. It will pass the same reference of the input field to the callback.

private string oldInputFieldValue;

public override void SetText(string newValue)
{
    Debug.Log("Old text: " + oldInputFieldValue);
    Debug.Log("Current text: " + newValue);
    oldInputFieldValue = newValue;
}

private void Start()
{
    editedText = new TextReceiver();
    textField.onValueChanged.AddListener(SetText);
}