【发布时间】:2022-01-16 13:01:51
【问题描述】:
我有一个 TextMeshPro 输入字段,但我在获取 Text 组件的各种尝试都产生了空引用异常。输入字段称为名称。当玩家在提交姓名后单击“确定”时,我会引用此对象。 这是 GetName 脚本:
public class GetName : MonoBehaviour
{
GameObject Name;
// These two are left over from previous attempts.
public TextMeshProUGUI player_name;
public TMP_InputField player_inputField;
private string monicker;
// Integer function should be less bother than a bool when called from another script.
public int IsNameEmpty()
{
monicker = Name.GetComponent<TMP_InputField>().text.ToString();
// Program never gets this far.
另一个脚本中的OK函数是:
public class WelcomeButtons : MonoBehaviour
{
public GetName getName;
void TaskOnClick6()
{
Debug.Log("You have clicked the OK button!");
int isName = getName.IsNameEmpty(); // Causes null reference exception.
// Program never gets this far.
【问题讨论】:
-
嗨佩扎。由于我没有看到您的代码中设置了您的游戏对象名称,您确定您引用了包含 TMP_InputField 的游戏对象吗?另一方面,如果您将 GetName-Component 附加到包含 TMP_InputField 的 GameObject,则可以更改“Name.GetComponent
().text.ToString();”到“GetComponent ().text.ToString();”。 -
感谢您的回复。 GetName 脚本附加到一个名为 NameControl 的空 GameObject。是否应该将其附加到输入字段?
标签: c# unity3d nullreferenceexception