Home > Blockchain >  Why can't I get the Text component of an Input Field
Why can't I get the Text component of an Input Field

Time:12-15

I have a TextMeshPro Input Field but my various attempts at getting the Text component are producing null reference exceptions. The Input Field is called Name. I reference this object when the player clicks OK after submitting their name. Here is the GetName script:

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.

The OK function in the other script is:

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.

CodePudding user response:

A simple method to get the text from the input field

public class GetName: MonoBehaviour
{
public TMP_InputField name;

public void TaskOnClick()
{
    if(name =="")
    {
     Debug.log("NO Name Found");
    }
    else
    {
    Debug.log("NAME: " name);
    }
}

CodePudding user response:

Yes, if you attached the script above to an empty GameObject, then your script is missing the Link to the GameObject containing the TMP_InputField-Component. You can fix this in two simple ways, just decide what fits best for you:

a) Attach the GetName-script to the same GameObject that also contains the TMP_InputField-Component. Replace the Line "Name.GetComponent<TMP_InputField>().text.ToString();" with "GetComponent<TMP_InputField>().text.ToString();".

b) Leave the GetName-script on the empty GameObject. Make the "GameObject Name;" line public by changing it to "public GameObject Name". Go to the Unity-Editor. When selecting the GameObject containing the GetName-script, you should see the Name-Property and an empty Field next to it in the Inspector. Drag&Drop the GameObject containing the TMP_InputField-Component into it.

So, why did your code not work before? Well, the GetName-script needs some kind of reference to your TMP_InputField-component, which was missing. You tried this by getting it from the Name-Property, but never assigned it any value.

  • Related