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

Question Using Game Objects in scripts/Grabbing Text Component from Input Fields

Discussion in 'UGUI & TextMesh Pro' started by SconeIsGone, Nov 6, 2020.

  1. SconeIsGone

    SconeIsGone

    Joined:
    Nov 6, 2020
    Posts:
    4
    EDIT: I finally figured out what I did wrong. When I assigned the Input Field to the variable inputFieldUsername I needed to specifically attach the text object of the input field, not the input field itself.

    Hello. I am complete beginner to Unity and C# scripting and I've been struggling to take the text inputted from an Input Field and put it into a variable within a script so I can use it.

    Here is the code I have so far. All it's supposed to be doing right now is taking the text inputted from inputFieldUsername and outputting that text into the log so I know that the text has been retrieved properly.

    Currently it's giving me a NullReferenceException on line 18 which I think is happening because I've not called the Input Field properly, but I'm not sure how to fix that. I'm also not entirely sure that I've used the right method to retrieve the text component on that line either but I've tried other methods like GetComponent which have given me errors before the code was run.
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class registrationScript : MonoBehaviour
    7. {
    8.     public InputField inputFieldUsername;
    9.     string chosenUsername;
    10.  
    11.     void Start()
    12.     {
    13.         Debug.Log("Script is alive");
    14.     }
    15.  
    16.     void OnClickRegistration()
    17.     {
    18.         chosenUsername = inputFieldUsername.text;
    19.         Debug.Log(chosenUsername);
    20.     }
    21. }
    Any help/advice you could give would be greatly appreciated. I have tried to look for answers elsewhere but no answer I've looked at has helped so far. Also, I'm pretty sure that it's better to use SerializeField rather than public on Line 8 but at this point I just want to get this code working before I make any changes like that. Thank you!
     
    Last edited: Nov 8, 2020
  2. SconeIsGone

    SconeIsGone

    Joined:
    Nov 6, 2020
    Posts:
    4
    I still haven't figured out what's causing the Null Reference Exception. Shouldn't that error only show up if the data at inputFieldUsername.text is empty? When I've been testing this script within the game environment I have been putting text into that Input Field to test it, so I'm really not sure what's causing this error. I really need an answer to this so if anyone can help it would be greatly appreciated.