using UnityEngine; using TMPro; [RequireComponent(typeof(TMP_InputField))] public class PostalCodeFormatter : MonoBehaviour { private TMP_InputField input; private bool isUpdating = false; private int pendingCaret = -1; // Format: L C L C L C // Index: 0 1 2 3 4 5 6 // Sans espace: L C L C L C (0 1 2 3 4 5) private void Awake() { input = GetComponent(); input.characterLimit = 7; input.onValueChanged.AddListener(OnValueChanged); } private void OnDestroy() { if (input != null) input.onValueChanged.RemoveListener(OnValueChanged); } private void LateUpdate() { if (pendingCaret >= 0) { input.caretPosition = pendingCaret; input.selectionAnchorPosition = pendingCaret; input.selectionFocusPosition = pendingCaret; pendingCaret = -1; isUpdating = false; } } private void OnValueChanged(string raw) { if (isUpdating || string.IsNullOrEmpty(raw)) return; // Enlever espaces et mettre en majuscules string clean = raw.ToUpper().Replace(" ", ""); // Filtrer selon le format L C L C L C string valid = ""; for (int i = 0; i < clean.Length && i < 6; i++) { char c = clean[i]; if (IsLetterPosition(i)) { // Position lettre : accepter seulement A-Z if (char.IsLetter(c)) valid += c; } else { // Position chiffre : accepter seulement 0-9 if (char.IsDigit(c)) valid += c; } } // Insérer espace après 3 caractères string formatted = valid; if (valid.Length > 3) formatted = valid.Insert(3, " "); if (formatted != raw) { isUpdating = true; input.text = formatted; pendingCaret = formatted.Length; } } private bool IsLetterPosition(int index) { // Format sans espace: L C L C L C // Index: 0 1 2 3 4 5 // Lettres aux positions 0, 2, 4 return index == 0 || index == 2 || index == 4; } }