Search code examples
textunity-game-enginenullreferenceexceptioninput-field

NullReferenceException when trying to get text from inputfield


I am new to unity and want to get a value from a input text field. I found this question Get text from Input field in Unity3D with C#, but when I execute it the same error always appear: NullReferenceExcpetion : Object reference not set to an instance of an object. It seems like a stupid mistake and I tried everything but can't seem to fix it. My code:

void Start () {
    var input = gameObject.GetComponent<InputField>();
    input.onEndEdit.AddListener(SubmitName);

}

private void SubmitName(string arg0)
{
    Debug.Log(arg0);
}

I tried putting InputField input; before the start function and erasing var but still no luck. If anyone can help me with this problem it would be much appreciated. Pictures of where my scripts are attached at the moment. enter image description here

enter image description here


Solution

  • Your code is nearly correct, if you have a look at the documentation, you have to call your method with function before calling the method name. It looks to me like you are mixing c# and JS, here is the `js function:

    public class Example {
        public var mainInputField;
        public function Start() {
            // Adds a listener to the main input field 
            // and invokes a method when the value changes.
            mainInputField.onValueChange.AddListener(function() {
                ValueChangeCheck();
            });
        }
        // Invoked when the value of the text field changes.
        public function ValueChangeCheck() {
            Debug.Log("Value Changed");
        }
    }
    

    the c# solution:

    public class MenuController : MonoBehaviour {
    
        [SerializeField]
        InputField inputText;
    
        // Use this for initialization
        void Start () {
            inputText.onValueChange.AddListener(delegate {
                DebugInput();
            });
        }
    
        private void DebugInput(){
            Debug.Log ("Input: " + inputText);
        }
    }
    

    My Hierarchie looks like this:

    I created a Canvas and inserted an InputField inside it. The script with the code inside is attached to the Canvas and the InputField connected to the [SerializeField] inside the script in the Canvas.


    I would recommend you to make your InputField a class variable, so you can access it easier later. Furthermore you should just create a [SerializeField] for your InputField so you can drag it to your script. This might avoid some mistakes too.