19

I'm trying to get a text inside an inputField in Unity3D with C#.

I've placed an inputField in my editor, renamed and tagged in: Username_field.

My question is: How i can get the text inside the InputField Username_field in a C# script?

Mirko Brombin
  • 1,002
  • 3
  • 12
  • 34
  • I've been able to do it with InputField.value. Example: String s = myInputField.value to get the value or myInputField.value = "Test" to set the value. – jadkins4 Feb 14 '15 at 18:45

3 Answers3

41

Attach below monobehaviour script to your InputField gameObject:

public class test : MonoBehaviour {
    void Start ()
    {
        var input = gameObject.GetComponent<InputField>();
        var se= new InputField.SubmitEvent();
        se.AddListener(SubmitName);
        input.onEndEdit = se;

        //or simply use the line below, 
        //input.onEndEdit.AddListener(SubmitName);  // This also works
    }

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

See also below animation:

enter image description here

David
  • 15,894
  • 22
  • 55
  • 66
4

You can use the "On Value Change" or "End Edit" event of the InputField.

The Unity3D documentation provides more detail on how to use a UnityEvent: http://docs.unity3d.com/Manual/UnityEvents.html

Alternatively, you should also be able to access the Text using the Text property of the Text control that your InputField is attached to.

Botz3000
  • 39,020
  • 8
  • 103
  • 127
  • In Unity 2017 you have to use the text component of the InputField (`String myText = myInputField.GetComponent().text;`) instead of the text component of the child text, otherwise an e.g. password field will only return asterisks (*). There's a warning about it [here](https://docs.unity3d.com/Manual/script-InputField.html). – Neph Aug 06 '18 at 12:31
1
using UnityEngine.UI;
public InputField betInput;
void Start () {
    betInput.onEndEdit.AddListener(delegate { inputBetValue(betInput); });
}
public void inputBetValue(InputField userInput)
{
    betValue = int.Parse(userInput.text);
    Debug.Log(userInput.text);
}

https://i.stack.imgur.com/CeF1a.png //This is unity Picture where you select method. Also worth checking out https://unity3d.com/learn/tutorials/topics/scripting/text-input

StaticVoid
  • 21
  • 1