如何使用 C# 在 Unity 5 中引用 InputField

How to reference an InputField in Unity 5 using C#

我想使用 C# 在 Unity 5 中引用 InputField,但不知道如何引用。

我的目标是在单击按钮时从 InputField 中获取文本,并将该文本用作项目其他部分中的变量。

我试过使用 GameObject.Find("IPInput").GetComponent<Text>(); 但这似乎不起作用。我正在使用 UnityEngine.UI 所以不是那样。

我认为您将静态 Text 组件与 InputField 混淆了。试试这个:

InputField field = GameObject.Find("IPInput").GetComponent<InputField>();
Debug.Log(field.text);

旁注,按游戏对象名称查询效率不高,因此根据您的操作,您可能只想将此字段添加到处理按钮单击的组件中:

public InputField field;

然后将输入字段拖到检查器中,您就不必调用 GameObject.Find()GetComponent()。比硬编码对象名称好得多。