I'm getting an error "Null Reference"when trying to get the component "InputField"

Even after connecting the game object itself, InputField, it still doesn’t work, anyone got a fix?
Now this is a monoscript.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class ButtonController : MonoBehaviour
{
    public GameObject theText;

    public void ClearText()
    {
        theText.GetComponent<InputField>().text = "";
    }
}

It’s very simple, one of these two problems:

  • you never assigned the theText reference in the inspector
  • The object you assigned doesn’t have an InputField component on it.

To eliminate the possibility of the second one and simplify your code you should just directly reference the InputField component, instead of going through the GameObject for no good reason:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class ButtonController : MonoBehaviour
{
    public InputField theText;
    public void ClearText()
    {
        theText.text = "";
    }
}

Then go and double check that the object is assigned properly in the inspector

I did assign it in the inspector, i used the script you gave me and I tried to assign the InputField but it didn’t assign somehow.

9912315--1432671--image_2024-06-27_230332086.png
9912315--1432674--image_2024-06-27_230440454.png

Most likely this reveals the entirety of the problem at hand. You’re probably using TextMeshPro - InputField, not the legacy InputField which would be this in code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class ButtonController : MonoBehaviour
{
    public TMP_InputField theText;
    public void ClearText()
    {
        theText.text = "";
    }
}

This is part of the benefit of the direct reference - it won’t even let you assign it if you’re using the wrong field type as you have been.

I tested this out and it worked! Thanks man, I really appreciate the help! Have a pleasant day/evening!