Get a OnTextChanged

Hi,

I would like to get a callback whenever I modify a Text.text value using Unity 5 new UI system.

Is it possible without making a noisy Update() check previous/current value ?

Thanks.

You could download the Code for the text component and add a event to the set function of the text field.
https://bitbucket.org/Unity-Technologies/ui/src/fadfa14d2a5cb8d6462db067e669b4b2bc11a018/UnityEngine.UI/UI/Core/Text.cs?at=5.1

Alternatively, if you don’t want to modify the source you could create an extension method for the Text class called SetText(). In it you could then do what @fffMalzbier suggested, though it would be a bit less clear as Text.text could still be modified as well.

I would Invoke the event inside of the set part of the text variable.
That way every time the text get changed you get the event.

Great suggestion, I just implement that:

using UnityEngine;
using UnityEngine.UI;

public static class TextExtension
{
    public static void SetText(this Text myText, string value)
    {
            Debug.Log("I change my text to \"" + value+ "\" ");
            myText.text = value;
    }
}

Just sharing since extension methods are a bit particular to write

2 Likes