我正在使用Unity编写游戏,但是我在Text Mesh Pro的输入框上遇到了On End Edit事件的问题。我需要在运行时(代码中)定义事件。我真的不知道如何解决这个问题。
以下是编辑器中事件的图片,我希望它连接到PlayerConnectionManager类中的PressedButton方法:
要求任何帮助!
答案 0 :(得分:2)
我假设你需要在运行时而不是通过编辑器调用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);
}
}
记住你给它的功能应该有一个带字符串的参数。即
PlayerConnectionManager.PressedButton
应该是上面提到的similer类型TextMeshUpdated(string text)
。这将允许它在运行时回调函数。
您必须记住的另一件事是,如果您在其他地方使用inputfield,请确保在添加新侦听器之前删除旧侦听器。
你可以用它来做到这一点
tmpInputField.onEndEdit.RemoveListener(TextMeshUpdated);
要么
tmpInputField.onEndEdit.RemoveAllListeners();
第一种方法只删除特定的函数回调,而RemoveAllListeners将删除附加到回调的所有事件监听器。如果你不这样做并尝试分配新的回调,它将尝试调用旧函数,并可能抛出一些错误。