I have scoured the unity forums and google trying to access an InputField text in C# and just cannot get it to work. I assume it is a simple error. These are the steps I have taken:
GameObject > UI > InputField
In a C# script attached to an empty object in the scene, I added this code
public class UIManagerScript : MonoBehaviour {
public GameObject initialsObject;
InputField initialsField;
Text initialsFieldInput;
public void Start(){
initialsField = initialsObject.GetComponent<InputField>();
initialsFieldInput = initialsField.GetComponent<Text>();
}
public void otherFunction(){
Debug.Log(initialsFieldInput.text);
// error: Object reference not set to an instance of an object
}
}
dragged the InputField object created in #1 from hierarchy to “Initials Object” in script inspector
As I understand it, when I create the InputField from the menu in #1, a GameObject is made with the InputField script attached. Is this correct?
No need to access via Text component. Text component is exposed via InputField.textComponent and value of that text is accessible via InputField.text. Hope this helps
just a side note (even though your issue has been solved)
the Text component text value is not guaranteed to be the same as the InputField text value. This is due to the inputfield modifying the string before using the Text component to display the value.
initialsFieldInput = initialsField.GetComponent(); isn’t needed for one. you can just do initialsField.textComponent (if you still want the Text component.
initialsField.text is all you need to get the full value of the input fields text.
but now i have another problem, if i use a Chinese Input Method, such as Sogo, if the IME has characters before the InputField Initialized, then the InputField.text will always get the characters before the value you set. How can I do?