Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Null Reference exception?

Discussion in 'Editor & General Support' started by MosquitoByte, Mar 14, 2020.

  1. MosquitoByte

    MosquitoByte

    Joined:
    Sep 17, 2018
    Posts:
    213
    I have an input field and a button, when the button is clicked, it takes the text from the input field and stores it as a variable, as such:
    Code (CSharp):
    1. TheName = Inputfield.GetComponent<Text>().text;
    however, when clicking the button, which calls the method to perform this action, this exact line throws the error: NullReferenceException: Object reference not set to an instance of an object.
     
  2. Olmi

    Olmi

    Joined:
    Nov 29, 2012
    Posts:
    1,553
    Hi @MosquitoByte

    If you want to access the text contents of the input field, try getting the InputField, not the Text element in it's hiearchy.

    If you were to get an input field (assuming the script is in the InputField unity object), you would do it like this:
    Code (CSharp):
    1.  // Get an InputField instance from this GameObject instance:
    2. var inputField = gameObject.GetComponent<InputField>();
    To access the user written text content:
    Code (CSharp):
    1. string myUserInput = inputField.text;
     
    Last edited: Mar 14, 2020