Saving data using Input Fields
Objective: Save data with Input Fields in Unity
Unity has Input Fields that we can easily set up and type into! We will set up two Input Fields right over top of each other. To add InputFields, in the Hierarchy rightclick → UI → Input Field — TextMeshPro.
I created another Text object below to display the username and password later.
Before moving on make sure you know which Input Field you are selecting. As shown above we are using the Text Mesh Pro, on older versions of Unity that option wont show up. I am using 2022.3 Unity. If you want the Input Field that uses the Text object go to Hierarchy and right click → UI → Legacy → Input Field.
Making sure which one you are using will help in the coding side. Create a new C# script. Grab the TMPro library.
Next we will create variable for the name and password input fields and a text for the output. Since we are using TextMeshPro in this article we will use the TMP_InputField. If you use the Legacy Input Field, grab the UnityEngine.UI library and use InputField instead.
Next is to create a method for Name input and password input. In each method we will use PlayerPrefs.SetString(string name, string value);, for each we will name the string accordingly. For the Value we will input, variable name plus .text. Ex. PlayerPrefs.SetString(“password”, _password.text);
PlayerPrefs is a way to store information on the users computer but it is not encrypted. You can refer to this unity documentation for more information.
For the last method we will set the text and for the name and password that we just got, we will use PlayerPrefs.GetString.
Back in Unity, we will attach this script to an object in the game. We can drop in the Input Field for Name and Password while also dropping in the text to be out putted.
We can disable the Password Input Field and text. We will activate them once we hit enter after entering something. To do this we will select an Input Field and in On End Edit event, we will add three events. For the First one drop in the Object with the script and select the InputName method. The Next one drop in the Password Input field, set active to true. The last one do the current selected Input Field and set active to false.
Select Password Input Field and do the same thing but activating the Text Field and calling the OutPut method.
With this we can enter names and passwords and have the computer print them back to us!
Thank you for reading! Have a wonderful day!