PIN Number verification in Unity
Objective: Create a Pin system to verify pin is correct.
We can use input fields to save pins and have them reenter them and verify it. To do this we will need two Input Fields. Create them by going in the Hierarchy and right click → UI → Input Field — TextMeshPro.
We will have them at the same location.
If you drop down the InputField, than Text Area and select Placeholder, you can change the text inside the Input Field.
We will also create a text and place it under the Input Fields.
Now we can create our script. In this script we will need the TMPro library. Also we will need two Input Field variables, a TMP_Text variable, and two int variables as well.
In start we will set the _debugText to have no value.
I created a method for a user to create their pin. First thing we will do is verify that the length is 4. If not set the debugText output there was an error. Next will be to clear the input field.
If the pin is 4 digits, we will save the pin to the int variable we created earlier. We will do this by using int.Parse(). This will take a string and turn it into a int. To verify what was inputed, I Debug.Log(_createdPin);. After that I turned off the create pin Input Field and activated the enter pin input field. The last thing for this method is to clear our the debugText again.
Now to verify the entered pin is correct. Create another method. First thing we will do is to save the pin to the enteredPin variable using the int.Parse again. Next will be to verify the enteredPin is the same as createdPin. If it is change debugText to let the user know, I used “Correct!”.
If they don’t match we will set the debugText to let the user know, I used “ You entered the wrong pin!”. The final thing will be to clear out the enteredPinField.
Attach the script to your game object and drop in the input fields and text objects.
To use the methods we created, select the input fields and in On Edit End, add an event, drop in the object that holds the script than select the method in the drop down.
Same thing for the entered pin field.
With that we have a working pin verification system.
Thank you for reading! Have a wonderful day!