Advertisement
LeeMace

Only Numbers Allowed as Input

Jun 16th, 2023
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.79 KB | Gaming | 0 0
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using TMPro;
  4.  
  5. public class NumericInputField : MonoBehaviour
  6. {
  7. //I used a serialized field instead of getting component
  8.      [SerializeField] TMP_InputField inputField;
  9.    // private InputField inputField;
  10.  
  11.     private void Start()
  12.     {
  13.        // inputField = GetComponent<InputField>();
  14.  
  15.         // Add the validation function to the onValidateInput event
  16.         inputField.onValidateInput += ValidateInput;
  17.     }
  18.  
  19.     private char ValidateInput(string text, int charIndex, char addedChar)
  20.     {
  21.         // Allow digits 0-9
  22.         if (char.IsDigit(addedChar))
  23.         {
  24.             return addedChar; // Accept the input
  25.         }
  26.  
  27.         // Reject all other characters
  28.         return '\0'; // Null character to block the input
  29.     }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement