How to use the TMP version of inputField in a script.

1 minute read

In the end, it looks like this.
ezgif.com-video-to-gif.gif

Please make your own settings such as using Japanese with Text Mesh Pro.
I will post a reference site about it ↓
Using Japanese fonts with TextMesh Pro [Unity]

Then, first select Create → UI → Input Field –Text Mesh Pro.
Then create an empty game object.

“shot” 2020-09-24 0.01.34.png

Next, create a new script.
The name of the script can be anything.
After creating the script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

Where it says using ~

using TMPro;

To add.

Then declare a variable of type “TMP_InputField”. Write like ↓.
Here, the name of the variable is “_inputField”.

public class Textscript : MonoBehaviour
{

    TMP_InputField _inputField;

    void Start()
    {

After that, find the GameObject of InputField (TMP) in Start and get “TMP_InputField” there.


    void Start()
    {
        _inputField = GameObject.Find("InputField (TMP)").GetComponent<TMP_InputField>();


    }

After that, create a function called “InputName” with “public”.
↓ It looks like this including the contents of the function.

    public void InputName()
    {
        string name = _inputField.text;
        Debug.Log(name);

        _inputField.text = "";
    }

As an explanation of the contents, put the text in the variable “_inputField” of the “TMP_InputField” type created earlier in the variable called name of string type.
Then output to the console with Debug.Log (name).
Feeling like that.
I will paste the whole script so far.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class Textscript : MonoBehaviour
{
    TMP_InputField _inputField;

    void Start()
    {
        _inputField = GameObject.Find("InputField (TMP)").GetComponent<TMP_InputField>();
    }

    void Update()
    {
        
    }

    public void InputName()
    {
        string name = _inputField.text;
        Debug.Log(name);
    }

}

That’s it for the script, and when you’re done, paste this script into the empty GameObject you just created.

Then press “+” of “On End Edit (String)” in the inspector view of “Input Field (TMP)” and drag an empty game object with a script in the “None” part.
There are various choices on the right, so look for the name of the script you created earlier, and select the function “InputName” you created earlier.
Then it will be like this ↓.

“shot” 2020-09-24 0.05.19.png

that’s all.
The characters you typed like the GIF image at the top should be output to the console.