在运行时从输入框 (Text Mesh Pro) 设置结束编辑事件

Set On End Edit Event from a Input Box (Text Mesh Pro) while runtime

我正在 Unity 中编写游戏,但我在使用 Text Mesh Pro 的输入框上的结束编辑事件时遇到问题。我需要在运行时(在代码中)定义事件。我真的不知道如何处理这个问题。

这是编辑器中事件的图片,我希望它连接到 class PlayerConnectionManager 中的 PressedButton 方法:

谢谢大家的帮助!

我假设您需要在运行时而不是通过编辑器调用 PlayerConnectionManager.PressedButton。如果是这样的话,那很容易。你只需要使用 addlistener。这是一个片段。

public class TextMeshAdd : MonoBehaviour 
{
    //input field object
    public TMP_InputField tmpInputField;

    // Use this for initialization
    void Start () 
    {
        //Add a listener function here
        //Note: The function has to be of the type with parameter string
        tmpInputField.onEndEdit.AddListener(TextMeshUpdated);
    }

    public void TextMeshUpdated(string text) 
    {
        Debug.Log("Output string "  + text);
    }
}

记住你给它的函数应该有一个带字符串的参数。 IE PlayerConnectionManager.PressedButton应该是上面提到的类似类型TextMeshUpdated(string text)。这将允许它在运行时回调函数。

您必须记住的另一件事是,如果您在其他地方使用输入字段,请确保在添加新侦听器之前删除旧侦听器。 你可以用这个来做 tmpInputField.onEndEdit.RemoveListener(TextMeshUpdated); 要么 tmpInputField.onEndEdit.RemoveAllListeners();

第一种方法将仅删除特定的函数回调,而 RemoveAllListeners 将删除附加到回调的所有事件侦听器。如果您不这样做并尝试分配新的回调,它将尝试调用旧函数,并且可能会抛出一些错误。