Max
Max

Reputation: 151

Check for text change event in Unity

I am using TextMeshPro with an input field. I am searching for a input character and replace it with another character. I can do it easily with Update() function but the calls are quite expensive. How do I create an event to check if a text field has been changed?

EDIT: Based on the user's answer, I did try to use onValueChanged, but I received an exception error - StackOverflowException: The requested operation caused a stack overflow.

using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;

public class TextChangeEvent : MonoBehaviour {
   
   public TMP_InputField textInput_;   
   
   public void Start(){
     textInput_.onValueChanged.AddListener (delegate { myTextChanged(); });
   }

   public void myTextChanged(){
     textInput_.text = textInput_.text.Replace("World", "Unity");
  }
}

Upvotes: 2

Views: 8896

Answers (2)

derHugo
derHugo

Reputation: 90620

Well what you are doing in

textInput_.text = textInput_.text.Replace("World", "Unity");

is changing the text
→ soooo again the event onValueChanged is called
→ again myTextChanged is called
→ it again changes the text
→ soooo again the event onValueChanged is called
→ .......... ENDLESS LOOP

What you can try to do is

public TMP_InputField textInput_;   
   
public void Start()
{
    // onValueChanged expects a `void(string)` so instead of adding an anonymous 
    // delegate you can never remove again rather make sure your method implements 
    // the correct signature and add it directly
    textInput_.onValueChanged.AddListener(myTextChanged);
}

// We need this signature in order to directly add and remove this method as 
// a listener for the onValueChanged event
public void myTextChanged(string newText)
{
    // temporarily remove your callback
    textInput_.onValueChanged.RemoveListener(myTextChanged);

    // change the text without being notified about it
    textInput_.text = newText.Replace("World", "Unity");

    // again attach the callback
    textInput_.onValueChanged.AddListener(myTextChanged);
}

In newer versions there is also directly

textInput_.SetTextWithoutNotify(newText.Replace("World", "Unity"));

which basically does what the name says: It sets the text value but doesn't invoke the onValueChanged event.

Upvotes: 2

Damian Piszka
Damian Piszka

Reputation: 125

Try this from Unity Documentation: OnValueChanged

Edit 1:
I researched a problem and i did read this post: Remove listener with one parameter in Unity
The problem is that you are changing the value when u detect a change, but this change you have done triggers in recurrency to infinity... So the solution is to remove the listener when you are changing value and then you need to add the listener again.

Upvotes: 1

Related Questions